Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a gradient of colors for a discrete variable in ggplot2?

Tags:

r

ggplot2

I have data with about 100 ordered categories. I would like to plot each category as a line separately, with the line colors ranging from a low value (say, blue) to a high value (say, red).

Here's some sample data, and a plot.

# Example data: normal CDFs

library(ggplot2)

category <- 1:100
X <- seq(0, 1, by = .1)
df <- data.frame(expand.grid(category, X))
names(df) <- c("category", "X")
df <- within(df, {
  Y <- pnorm(X, mean = category / 100)
  category <- factor(category)
  })

# Plot with ggplot
qplot(data = df, x = X, y = Y, color = category, geom = "line")

This produces a pretty rainbow thing (below)enter image description here

but I'd rather have a gradient from blue to red. Any ideas how I can do that?

like image 523
Jake Fisher Avatar asked May 20 '15 14:05

Jake Fisher


People also ask

How to change the gradient color in ggplot?

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.

How do I specify colors in ggplot2?

To specify colors of the bar in Barplot in ggplot2, we use the scale_fill_manual function of the ggplot2 package. Within this function, we need to specify a color for each of the bars as a vector. We can use colors using names as well as hex codes.

How to specify group colors in ggplot2?

When creating graphs with the ggplot2 R package, colors can be specified either by name (e.g.: “red”) or by hexadecimal code (e.g. : “#FF1234”). It is also possible to use pre-made color palettes available in different R packages, such as: viridis, RColorBrewer and ggsci packages.


2 Answers

The default gradient functions for ggplot expect a continuous scale. The easiest work around is to convert to continuous like @Roland suggested. You can also specify whatever color scale you want with scale_color_manual. You can get the list of colors ggplot would have used with

cc <- scales::seq_gradient_pal("blue", "red", "Lab")(seq(0,1,length.out=100))

This returns 100 colors from blue to red. You can then use them in your plot with

qplot(data = df, x = X, y = Y, color = category, geom = "line") +     
    scale_colour_manual(values=cc)

enter image description here

like image 149
MrFlick Avatar answered Sep 22 '22 14:09

MrFlick


Since a discrete legend is useless anyway, you could use a continuous color scale:

ggplot(data = df, aes(x = X, y = Y, color = as.integer(category), group = category)) +
  geom_line() +
  scale_colour_gradient(name = "category", 
                        low = "blue", high = "red")

resulting plot

like image 40
Roland Avatar answered Sep 26 '22 14:09

Roland