0

I am trying to plot a graph on ggplot and I want to change the title of the legend and also the values there. I tried all methods explained How to change legend title in ggplot ; however, non of these methods works for me.

structure(list(sold_date_yq = structure(c(2014.5, 2014.75, 2014.75, 
2015, 2015, 2015.25, 2015.25, 2015.5, 2015.5, 2015.75, 2015.75, 
2016, 2016, 2016.25, 2016.25, 2016.5), class = "yearqtr"), V_tour_update = c(1, 
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0), average_sold_sqft = c(646.354142011834, 
623.121985926505, 678.629387755102, 651.493616045845, 666.909525139665, 
671.250383912249, 680.049114583333, 698.693468862584, 699.523971830986, 
718.077661016949, 759.139753521127, 791.252619047619, 814.418133704735, 
836.438735902256, 884.5826, 849.757720754717)), row.names = c(NA, 
-16L), groups = structure(list(sold_date_yq = structure(c(2014.5, 
2014.75, 2015, 2015.25, 2015.5, 2015.75, 2016, 2016.25, 2016.5
), class = "yearqtr"), .rows = structure(list(1L, 2:3, 4:5, 6:7, 
    8:9, 10:11, 12:13, 14:15, 16L), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, 9L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

and I tried to plot this with

ggplot(a, aes(x=sold_date_yq, y=average_sold_sqft)) +
  geom_line(aes(color=as.factor(V_tour_update)), size = 1) + scale_x_yearqtr(format="%YQ%q",n=6) + scale_y_continuous(limits = c(300,1200))+ 
  theme(legend.position="right")+
  theme(plot.title = element_text(hjust = 0.5, size=10))+
  theme_bw()+ theme(axis.text.x = element_text(angle = 90, vjust=0, hjust=1))+
  theme(legend.position=c(0.8, 0.1))

I want to change both the title of the legend and the values, so instead of 0 and 1, I use my own description.

and here is the result: enter image description here

Ross_you
  • 881
  • 5
  • 22

1 Answers1

2

You can use scale_color_manual -

ggplot(a, aes(x=sold_date_yq, y=average_sold_sqft)) +
  geom_line(aes(color=as.factor(V_tour_update)), size = 1) + 
  scale_x_yearqtr(format="%YQ%q",n=6) + 
  scale_y_continuous(limits = c(300,1200))+ 
  theme(legend.position="right")+
  theme(plot.title = element_text(hjust = 0.5, size=10))+
  theme_bw()+ theme(axis.text.x = element_text(angle = 90, vjust=0, hjust=1))+
  theme(legend.position=c(0.8, 0.1)) +
  scale_color_manual(labels = c('A', 'B'), values = factor(c('0', '1')), 
                     name = 'new name')

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213