Plot a single geom_smooth curve instead of multiple [duplicate]

南笙酒味 提交于 2019-12-01 11:12:11

问题


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")) 

回答1:


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"))



回答2:


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.


来源:https://stackoverflow.com/questions/47883446/plot-a-single-geom-smooth-curve-instead-of-multiple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!