[英]ggplot2: merge legends for geom_line, geom_point, and geom_bar
[英]ggplot2 - combining geom_bar and geom_line legend
我似乎无法将我的 geom_bar 和 geom_line 图例结合起来。 我知道关于这个主题有几个讨论,我想我已经尝试了大多数建议但没有成功,但我认为我不理解这个问题。 由于我在这方面花了几个小时并没有取得任何进展,我认为是时候询问专家了。 谢谢你的帮助!
我的数据:
A <-data.frame("X"= 1:6, "New" = c(5,25,10,43,2,3), "Recaptured" = c(0,2,20,20,29,14), "Cumulative" = c(5,30,40,83,85,88))
我的代码:
A$X<-factor(A$X, levels=A$X)
A[A==0]<-NA
p1<-A %>%
gather(key,value,New,Recaptured) %>%
ggplot(aes(x=X, y=value, fill=key, color="Cumulative"))+
geom_line(aes(y=Cumulative,group=1), size=1.25)+
geom_bar(stat="identity", width = 0.4, position = position_dodge(), color="black")+
scale_fill_grey(start = 0, end = 0.9)+
xlab(NULL)+
ylab(NULL)+
ggtitle("none")+
theme_minimal()+
theme(axis.title.x = element_text(size = 12, hjust = 0.35))+
theme(plot.title = element_text(hjust = 0.5)) +
#theme(plot.margin = margin(t=4,1,1,1, "lines"))+
theme(legend.direction="horizontal") +
theme(legend.position = c(.25, 0.9))+
theme(legend.background = element_rect(fill = "white", linetype = "solid", color="black"))+
theme(legend.title = element_blank())
p1
当前 plot:在此处输入图像描述
这个怎么样? 我基本上只是通过使用legend.spacing.y = unit(0.0, 'cm')
删除了图例之间的垂直空间,并将legend.background
参数更改为element_blank()
因为这个参数将在每个单独的图例周围创建一个框,它不是您想要的,并添加了legend.box.background
参数以一次围绕两个图例绘制一个框。
A %>%
ggplot(aes(x=X, y=value, fill=key, color="Cumulative"))+
geom_line(aes(y=Cumulative,group=1), size=1.25)+
geom_col(width = 0.4, position = position_dodge(), color="black")+
scale_fill_grey(start = 0, end = 0.9)+
xlab(NULL) +
ylab(NULL) +
ggtitle("My title") +
theme_minimal() +
theme(
axis.title.x = element_text(size = 12, hjust = 0.35),
plot.title = element_text(hjust = 0.5),
legend.direction="horizontal",
legend.position = c(0.5, 1.2),
legend.background = element_blank(),
legend.box.background = element_rect(size = 1),
legend.title = element_blank(),
plot.margin = margin(4, 1, 1, 1, "lines"),
legend.box = "horizontal",
legend.spacing.y = unit(0.0, 'cm')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.