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
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))
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.
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.
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.
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
The fill colour is saved in p$layers[[1]]$aes_params$fill
and can be modified this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With