Reputation: 726
My issue is that the variable that I am grouping by and assigning to color
is a continuous variable (numbers from 1:10), so the color will be a gradient. But I need each group to be a different color and not a gradient. How would I achieve this? Code and result below. The Date variable is below also.
library(ggplot2)
Date <-
c("12/31/2021", "12/31/2022", "12/31/2023", "12/31/2024", "12/31/2025",
"12/31/2026", "12/31/2027", "12/31/2028", "12/31/2029", "12/31/2030",
"12/31/2031", "12/31/2032")
a <- data.frame(id = rep(c(1,2,3),4), date = Date, income = rnorm(12, 60000, 15000))
a$date <- as.Date(a$date,"%m/%d/%Y")
ggplot(a,aes(x = date,y = income,group = id, color = id)) +
geom_line(size = 0.5)
Upvotes: 7
Views: 6319
Reputation: 9819
As already mentioned in the comments, you can use as.factor
in the color argument.
To define the colors used you can use scale_colour_manual
and either assign colors yourself or use the colorRampPalette
function.
ggplot(a,aes(x = date,y = income,group = id, color = as.factor(id))) +
geom_line(size = 0.5)
ggplot(a,aes(x = date,y = income,group = id, color = as.factor(id))) +
scale_colour_manual(values=c("green","red","blue")) +
geom_line(size = 0.5)
gs.pal <- colorRampPalette(c("red", "blue"))
ggplot(a,aes(x = date,y = income,group = id, color = as.factor(id))) +
scale_colour_manual(values=gs.pal(length(unique(a$id)))) +
geom_line(size = 0.5)
Upvotes: 5