0

I'm trying to made the text in the legend the same colour as the line in a ggplot. Say the line for Female is green and male is blue then the text saying female would be green and male would be blue.

df1 <- data.frame(
sex = factor(c("Female","Female","Male","Male")),
time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(13.53, 16.81, 16.24, 17.42))

ggplot(data=df1, aes(x=time, y=total_bill, group=sex, shape=sex, colour=sex)) + 
geom_line()+
scale_color_manual("sex",values=c("green", "blue"))

Test code taken from: http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/

user2946746
  • 1,740
  • 3
  • 21
  • 36
  • [this can help](http://stackoverflow.com/questions/23588127/match-legend-text-color-in-geom-text-to-symbol/23593663#23593663), but you will need to change `GRID.text` to `geom_path` in the fourth (or there abouts) line of the function – user20650 Mar 21 '15 at 00:28
  • http://stackoverflow.com/questions/2409357/how-to-nicely-annotate-a-ggplot2-manual/9081281#9081281 gives a nice way to include text as part of the plot rather than using an outside legend – user20650 Mar 21 '15 at 00:46
  • Thanks, I'm trying to work through the [example](http://stackoverflow.com/questions/23588127/match-legend-text-color-in-geom-text-to-symbol/23593663#23593663) but I'm getting stuck on the get grobs for legend labels. my list is empty on that light. I'm guessing this is because I'm using a different plot. Any idea on how I could correct this? – user2946746 Mar 26 '15 at 18:01
  • Hi, is the difficulty with the plot in your example or using your real data? When you use `ggplotGrob(p)` do you see the `guide-box` in the gtable. – user20650 Mar 26 '15 at 23:05
  • Yes, I'm using different data from the eia where I generate data through a custom function for different data sets. I have created an [example](http://stackoverflow.com/questions/29286588/how-to-create-a-custom-legends-using-ggplotgrob) with how I edited that function to create a custom legend. – user2946746 Mar 27 '15 at 16:05

0 Answers0