0

i need the plan legend

How to add a legend manually for geom_line

ggplot(data = impact_end_Current_yr_m_actual, aes(x = month, y = gender_value)) + 
    geom_col(aes(fill = gender))+theme_classic()+
    geom_line(data = impact_end_Current_yr_m_plan, aes(x=month, y= gender_value, group=1),color="#288D55",size=1.2)+
    geom_point(data = impact_end_Current_yr_m_plan, aes(x=month, y=gender_value))+
    theme(axis.line.y = element_blank(),axis.ticks = element_blank(),legend.position = "bottom", axis.text.x = element_text(face = "bold", color = "black", size = 10, angle = 0, hjust = 1))+
    labs(x="", y="End Beneficiaries (in Num)", fill="")+
    scale_fill_manual(values=c("#284a8d", "#00B5CE","#0590eb","#2746c2"))+
    scale_y_continuous(labels = function(x) format(x, scientific = FALSE)
Fariya
  • 234
  • 1
  • 11
  • 1
    What do you want to achieve exactly? How many levels does the legend should have? Only one? Does this help? https://stackoverflow.com/questions/40833809/add-legend-to-geom-line-graph-in-r – adelriosantiago Dec 08 '20 at 06:33
  • as per the above code i get legends for gender but i need to add the legend of geom_line in the same line @adelriosantiago – Fariya Dec 08 '20 at 07:25
  • For clarification i added the image kindly watch @adelriosantiago – Fariya Dec 08 '20 at 07:47

1 Answers1

0

The neatest way to do it I think is to add colour = "[label]" into the aes() section of geom_line() then put the manual assigning of a colour into scale_colour_manual() here's an example from mtcars (apologies that it uses stat_summary instead of geom_line but does the same trick):

library(tidyverse)

mtcars %>% 
  ggplot(aes(gear, mpg, fill = factor(cyl))) +
  stat_summary(geom = "bar", fun = mean, position = "dodge") +
  stat_summary(geom = "line", 
               fun = mean, 
               size  = 3, 
               aes(colour = "Overall mean", group = 1)) +
  scale_fill_discrete("") +
  scale_colour_manual("", values = "black")

Created on 2020-12-08 by the reprex package (v0.3.0)

The limitation here is that the colour and fill legends are necessarily separate. Removing labels (blank titles in both scale_ calls) doesn't them split them up by legend title.

In your code you would probably want then:

...
ggplot(data = impact_end_Current_yr_m_actual, aes(x = month, y = gender_value)) + 
    geom_col(aes(fill = gender))+
    geom_line(data = impact_end_Current_yr_m_plan, 
              aes(x=month, y= gender_value, group=1, color="Plan"), 
              size=1.2)+
    scale_color_manual(values = "#288D55") +
...

(but I cant test on your data so not sure if it works)

Andy Baxter
  • 5,833
  • 1
  • 8
  • 22