简体   繁体   English

在组合的ggplot2图上显示图例 - 堆积条和线

[英]Display legends on a combined ggplot2 plot - Stacked bar and line

I have a ggplot, which is a combination of a stacked graph and line graph 我有一个ggplot,它是堆叠图和折线图的组合

  ggplot() +
       geom_bar(data=smr2, aes(x=Pract, y=value, fill=variable), stat='identity') + 
       theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) +
       geom_line(data=summarised[,1:3], aes(x=Pract,y=YTDTarget, group=1),size = 1) +
       geom_point(data=summarised[,1:3], mapping = aes(x = Pract, y = YTDTarget),size=2.5)+
       geom_text_repel(data=summarised[,1:3], aes(x=Pract,y=YTDTarget,label=YTDTarget), size = 5)

I want to add the legend for line graph. 我想为折线图添加图例。 But the part group=1 seems to prevent this. 但是部分group=1似乎阻止了这一点。

The graph I created is as 我创建的图表是 在此输入图像描述

Also, please help to change the name of the legend from variable to "Actuals" This graph is for compare the Target(line graph) against actually achieved(stacked Bar). 另外,请帮助将图例的名称从变量更改为“Actuals”此图表用于比较Target(折线图)与实际实现的(堆叠条形图)。

Please try this: 请试试这个:

To geom_line add dummy variable (to add it to legend - in this case I'm using linetype ). geom_line添加虚拟变量(将其添加到图例 - 在这种情况下我使用的是linetype )。

geom_line(data = summarised[,1:3], 
          aes(Pract, YTDTarget, group = 1, linetype = ""),
          size = 1)

To change legend name add labs() to your plot. 要更改图例名称,请将labs()添加到绘图中。

labs(fill = "Actuals",
     linetype = "My Line Name")

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

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