[英]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,它们可以采用fill
和colour
参数。
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
使用fill
和colour
,是否可以选择在图例键( fill
或colour
)上映射的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.