简体   繁体   English

ggplot2填充和颜色映射图例

[英]ggplot2 fill and colour mapping legend

I have a sample data frame with four variables and I'm trying to map h variable to fill and s variable to shape . 我有一个带有四个变量的示例数据框,并且我试图将h变量映射为fill ,将s变量映射为shape Since my s variable can take only two values (either 'f' or 'u') I want to use geom_point 24 and 21 which can take fill and colour argument. 由于我的s变量只能采用两个值(“ f”或“ u”),因此我想使用geom_point 24和21,它们可以采用fillcolour参数。

library(ggplot2)
h <- c(1,2,3,4,5)
x <- seq(1:5)
y <- c(1,3,3,5,5)
s <- c(rep('f',3),rep('u',2))
dt <- data.frame(h,x,y,s)

Ideally, my geom_point would have black outline and coloured fill . 理想情况下,我的geom_point将具有黑色轮廓和彩色fill I can plot this with the below code and it produces this plot: 我可以使用以下代码来绘制此图,并生成以下图:

ggplot(dt, aes(x=y, y=x)) +  
    geom_point(mapping = aes(fill = factor(h), shape = s), size = 5) +
    scale_shape_manual(values = c(24, 21))

颜色由填充控制

I cannot get legend to display coloured keys since colour of legend key is mapped to colour not to fill . 我无法使图例显示彩色键,因为图例键的colour映射为不fill colour

I can have coloured legend keys if I change my geom_point to 19 and 17 and map my h variable colour : 如果将geom_point更改为19和17并映射h变量colour则可以使用彩色图例键:

ggplot(dt, aes(x=y, y=x)) +  
    geom_point(mapping = aes(colour = factor(h), shape = s), size = 5) +
    scale_shape_manual(values = c(19, 17))

颜色受颜色控制

Legend is displayed with coloured keys but black outline on my points on plot is gone. 图例用彩色键显示,但是我在绘图上的点上的黑色轮廓消失了。

Is there any way to choose what is mapped on legend key ( fill or colour ) if I used both fill and colour for geom_point ? 如果我对geom_point使用fillcolour ,是否可以选择在图例键( fillcolour )上映射的geom_point

ggplot(dt, aes(x=y, y=x)) +  
    geom_point(mapping = aes(fill = factor(h), shape = s), size = 5) +
    scale_shape_manual(values = c(24, 21)) +
    guides(fill=guide_legend(override.aes=list(shape=21)))

Above code produces this plot - exactly as I wanted, credits to bdemarest 上面的代码产生了这个图-正是我想要的,归功于bdemarest

fill mapped to legend 填充映射到图例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM