Arun GK
Arun GK

Reputation: 85

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() +
       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.

The graph I created is as enter image description here

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).

Upvotes: 1

Views: 2678

Answers (1)

pogibas
pogibas

Reputation: 28369

Please try this:

To geom_line add dummy variable (to add it to legend - in this case I'm using 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(fill = "Actuals",
     linetype = "My Line Name")

Upvotes: 3

Related Questions