Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...