![](/img/trans.png)
[英]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.