-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!

Roelalex1996
  • 53
  • 1
  • 7
  • 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
  • 377,200
  • 20
  • 156
  • 213