Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...