Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of gradient and use individual colors in ggplot?

Tags:

r

ggplot2

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)

enter image description here

like image 318
SantiClaus Avatar asked Jul 15 '18 16:07

SantiClaus


People also ask

How do you extract color from a gradient?

Have the Gradient, Color and Swatches panels open. Click the object colored with the gradient. Now click on the gradient stop you want to save as a swatch; It will appear as a solid box or as the Fill in the Color panel. Drag that from the Color panel to the Swatches panel, and you've saved it.

How do I specify colors in ggplot2?

A color can be specified either by name (e.g.: “red”) or by hexadecimal code (e.g. : “#FF1234”).

How do you change the gradient color in R?

Key functions to change gradient colors The default gradient colors can be modified using the following ggplot2 functions: scale_color_gradient() , scale_fill_gradient() for sequential gradients between two colors. scale_color_gradient2() , scale_fill_gradient2() for diverging gradients.

What colors does Ggplot recognize?

By default, ggplot2 chooses to use a specific shade of red, green, and blue for the bars. Here's how to interpret the output: The hex color code for the red in the plot is #F8766D. The hex color code for the green in the plot is #00BA38.


1 Answers

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)
like image 70
SeGa Avatar answered Oct 19 '22 11:10

SeGa