-1

I have this code:

testPlot= ggplot(residFrame) +
  geom_point(aes(x=STATEFP, y=total_diff, colour='total'), colour='red', shape=1) +
  geom_point(aes(x=STATEFP, y=desalination_diff, colour='desalination'), colour='blue', shape=1) + 
  geom_point(aes(x=STATEFP, y=surfacewater_diff), colour='green', shape=1) +
  geom_point(aes(x=STATEFP, y=groundwater_diff), colour='yellow', shape=1) +
  xlab('STATEFP') + ylab('Difference') + ggtitle('Difference for all states', subtitle='For each source')
testPlot

And now I want to add a legend to testPlot that describes what the colours in the plot represent. I have searched the web, but cannot find the answer to this particular problem, can someone help me out here?

Thanks!

  • 3
    Does this answer your question? [regrading adding a legend using ggplot2 for different lines](https://stackoverflow.com/questions/61730874/regrading-adding-a-legend-using-ggplot2-for-different-lines) – DS_UNI Nov 09 '20 at 08:57

1 Answers1

0

You should get the data in long format and then plot instead of calling geom_point multiple times. You have not provided an example of your data but you can try.

library(ggplot2)

residFrame %>%
  tidyr::pivot_longer(cols = ends_with('diff')) %>%
  ggplot() + aes(STATEFP, value, color = name) + 
  geom_point(shape = 1) + 
  xlab('STATEFP') + ylab('Difference') + 
  ggtitle('Difference for all states', subtitle='For each source')
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
  • Thanks, works perfect! Is there also a way to change the title of the legend? – Roelalex1996 Nov 09 '20 at 10:43
  • You can have a look here - https://stackoverflow.com/questions/14622421/how-to-change-legend-title-in-ggplot – Ronak Shah Nov 09 '20 at 10:51
  • @Roelalex1996 Glad to have been help! Feel free to [accept the answer](https://stackoverflow.com/help/someone-answers) by clicking on check mark to the left. You can accept only one answer per post. – Ronak Shah Nov 10 '20 at 01:22