Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the color of a ggplot geom a posteriori (after having specified another color)

Tags:

plot

r

ggplot2

A function from a package returns a ggplot with preset colours that I'd like to change.

For example, let's simulate that plot:

library(ggplot2)
df <- data.frame(x = rnorm(1000))

p <- ggplot(df, aes(x=x)) +
  geom_density(fill="#2196F3")
p

It is a blue-filled density plot.

I'd like to change its color a posteriori.

I've tried doing:

p + scale_fill_manual(values=c("#4CAF50"))
p

But it doesn't change anything.

I've also tried:

p <- p + geom_density(fill="black")
p

But that adds a layer on top of the previous one, without changing it.

I've also attempted to dig into the ggplot object but I got lost there.

Is there any convenient way to change the properties of a geom a posteriori?

Thanks

like image 494
Dominique Makowski Avatar asked Jan 11 '18 14:01

Dominique Makowski


People also ask

How to change the background color of a ggplot2 plot?

You can use the following syntax to change the background color of various elements in a ggplot2 plot: p + theme (panel.background = element_rect (fill = 'lightblue', color = 'purple'), panel.grid.major = element_line (color = 'red', linetype = 'dotted'), panel.grid.minor = element_line (color = 'green', size = 2))

How do I create a line plot in ggplot2?

library(ggplot2) #create line plot ggplot (df, aes (x=week, y=sales, group=store, color=store)) + geom_line (size=2) By default, ggplot2 uses a default color palette with red, green, and blue for the lines.

How to adjust the colors of the lines in a line plot?

The colors of the lines are corresponding to the default color palette of the ggplot2 package. The following code explains how to adjust the colors of the lines in our line plot using the scale_color_manual function. As you can see below, we have to specify a vector of colors within the scale_color_manual.

How to change the color of the line graph by default?

Let us look at one example to depict what the color of the line graph is by default. The color of the line graph can be changed in various ways. For this simply value for color attribute as the name of the column on which the values will be distinguished.


Video Answer


1 Answers

Try this:

#this is blue
p <- ggplot(df, aes(x=x)) +
  geom_density(fill="#2196F3")

#convert to red
p$layers[[1]]$aes_params$fill <-  'red'
p

enter image description here

The fill colour is saved in p$layers[[1]]$aes_params$fill and can be modified this way.

like image 95
LyzandeR Avatar answered Sep 21 '22 20:09

LyzandeR