Home > database >  Issue in changing the legend title in ggplot2
Issue in changing the legend title in ggplot2

Time:10-16

I have the dataframe below

d1_5<-structure(list(conm = c("Tesla Inc", "Tesla Inc", "Tesla Inc", 
"Tesla Inc", "Tesla Inc", "Tesla Inc", "Tesla Inc", "Tesla Inc", 
"Tesla Inc", "Tesla Inc", "Tesla Inc", "Tesla Inc", "Tesla Inc", 
"Tesla Inc", "Tesla Inc", "Tesla Inc", "Tesla Inc", "Tesla Inc", 
"Tesla Inc", "Tesla Inc", "Tesla Inc", "Tesla Inc"), datadate = structure(c(14974, 
14974, 15339, 15339, 15705, 15705, 16070, 16070, 16435, 16435, 
16800, 16800, 17166, 17166, 17531, 17531, 17896, 17896, 18261, 
18261, 18627, 18627), label = "Data Date", format.stata = "%td", class = "Date"), 
    fin_var = c("mkt_val", "sale", "mkt_val", "sale", "mkt_val", 
    "sale", "mkt_val", "sale", "mkt_val", "sale", "mkt_val", 
    "sale", "mkt_val", "sale", "mkt_val", "sale", "mkt_val", 
    "sale", "mkt_val", "sale", "mkt_val", "sale"), fin_value = c(2481.43666, 
    116.744, 2867.10984, 204.242, 3635.91063, 413.256, 17964.381609, 
    2013.496, 27698.71899, 3198.356, 30769.76202, 4046.025, 30816.66228, 
    7000.132, 51608.7533, 11758.751, 56750.72, 21461.268, 74044.41, 
    24578, 658390.11, 31536)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -22L))

and Im trying to change the legend title with the code below based on this without result:

p<-ggplot(d1_5, aes(x=datadate, y=fin_value, group=fin_var))  
  geom_line(aes(color=fin_var)) 
  geom_point(aes(color=fin_var)) 
  ylab("")   xlab("Date") 
  theme(legend.position="top") 
  scale_y_continuous( labels=scales::dollar_format())
p   guides(fill=guide_legend(title="New Legend Title"))

CodePudding user response:

You're setting it for the wrong aesthetic. Try color instead of fill:

ggplot(d1_5, aes(x=datadate, y=fin_value, group=fin_var))  
  geom_line(aes(color=fin_var)) 
  geom_point(aes(color=fin_var)) 
  ylab("")   xlab("Date") 
  theme(legend.position="top") 
  scale_y_continuous( labels=scales::dollar_format())   
  labs(color = "New Legend Title")
#   guides(color = guide_legend(title = "New Legend Title")) # also works
  • Related