I am trying to create a scatter plot to show the relationship between displacement and highway mpg in the mpg
dataset. Set the point size as 5 and set different colors for cars in 1999 and cars in 2008. The code I have right now is:
# Create a scatter plot to show the relationship between displacement and highway mpg
# Set point size as 5
# Set different colors for cars in 1999 and cars in 2008
library(ggplot2)
ggplot(mpg, aes(x = displ,y = hwy))
geom_point(aes(colour = cut(year, c(1999, 2008)), size = 5))
scale_color_manual(name = "year", values = c("1999" = "blue",
"2008" = "red") )
When I try this, there is a box that shows that 1999 should be blue and 2008 should be red, but the graph that is outputted doesn't correlate with the colors and is just gray. Can anyone help me out with what is happening here?
here is an image of the graph:
CodePudding user response:
library(ggplot2)
ggplot(mpg, aes(x = displ,y = hwy, col = factor(year),size = 5))
geom_point()
scale_color_manual(
values = c("1999" = "blue","2008"="red"),
name = "year"
)
CodePudding user response:
Another option using dplyr
to add a column with the colors to each year like this:
library(ggplot2)
library(dplyr)
mpg %>%
mutate(colors = case_when(year == 1999 ~ '1',
year == 2008 ~ '2')) %>%
ggplot(aes(x = displ,y = hwy, color = colors))
geom_point(size = 5)
scale_color_manual('year', values = c('1' = 'blue', '2' = 'red'), labels = c('1999', '2008'))
Created on 2022-09-25 with reprex v2.0.2