改变一个ggplot geom的颜色(在指定了另一种颜色之后) [英] Change the color of a ggplot geom a posteriori (after having specified another color)

查看:741
本文介绍了改变一个ggplot geom的颜色(在指定了另一种颜色之后)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数从一个包中返回一个带有预设颜色的ggplot,我想改变它。



例如,让我们模拟那个图:

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

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

这是一个蓝色填充的密度图。



我想后天改变它的颜色。



我尝试过:

pre $ scale_fill_manual(values = c( #4CAF50))
p

但它没有改变任何东西。



我也试过:

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

但是,在前一个图层上添加了一个图层,没有改变它。



我也试图挖掘ggplot对象,但我迷路了。



是否有任何方便的方法来改变geom a posteriori的属性?



谢谢 试试看

这:

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

#转换为红色
p $ layers [[1]] $ aes_params $ fill< - 'red'
p



填充颜色保存在 p $ layers [[1]] $ aes_params $ fill 中,并且可以用这种方式修改。


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

解决方案

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.

这篇关于改变一个ggplot geom的颜色(在指定了另一种颜色之后)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆