问题
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 bothgeom_point
andgeom_smooth
should be colored byregion
. - 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