3

I am plotting a graph with 3 different categories that are represented by different colours. I want one curve to represent the trend of the total data, but when I use geom_smooth I get 3 curves, one for each category. My code is:

#plot the data
ggplot(data=transfer_data, aes(x=DATE_OF_TRANSFER, y=NUMBER_OF_TRANSFERS, colour = region)) + geom_point() + geom_smooth() + scale_colour_manual(values=c("green", "blue", "red", "orange")) 
roberrrt-s
  • 7,914
  • 2
  • 46
  • 57
lewisnix21
  • 111
  • 2
  • 7

2 Answers2

7

There are two ways of solving this: 1) Override color aestetic in geom_smooth layer

   #plot the data
   ggplot(data=transfer_data, 
          mapping=aes(x=DATE_OF_TRANSFER, 
                      y=NUMBER_OF_TRANSFERS, 
                      colour = region)) + 
    geom_point() + 
    geom_smooth(color="black") + 
    scale_colour_manual(values=c("green", "blue", "red", "orange"))

or 2) Move color aestetic only to layer(s) that need it

   #plot the data
   ggplot(data=transfer_data, 
          mapping=aes(x=DATE_OF_TRANSFER, 
                      y=NUMBER_OF_TRANSFERS)) + 
    geom_point(mapping=aes(colour = region)) + 
    geom_smooth() + 
    scale_colour_manual(values=c("green", "blue", "red", "orange"))
dmi3kno
  • 2,943
  • 17
  • 31
1

You should use:

library(ggplot2)
ggplot(transfer_data, aes(DATE_OF_TRANSFER, NUMBER_OF_TRANSFERS)) + 
    geom_point(aes(color = region)) + 
    geom_smooth() + 
    scale_colour_manual(values = c("green", "blue", "red", "orange"))
  • When you specify: ggplot(data=transfer_data, aes(x=DATE_OF_TRANSFER, y=NUMBER_OF_TRANSFERS, colour = region)) you ask that both geom_point and geom_smooth should be colored by region.
  • When specifying: geom_point(aes(color = region)) + geom_smooth() you ask for points to be colored be region and smooth line to be the same for all regions.
pogibas
  • 27,303
  • 19
  • 84
  • 117