使用来自ggplot2图表的默认填充颜色,通过R中的注释

时间:2014-01-15 21:27:03

标签: r graph colors ggplot2 visualization

我想从ggplot2访问默认行或填充颜色,我不知道如何做到这一点。具体来说,在下面的代码中,您会在注释中看到 green4 blue4 red4 。这些是我认为ggplot2正在使用的近似

此外,如果此代码未遵循最佳做法或可能从替代方法中受益,请提供建议。

library(ggplot2)
ggplot(data.frame(x = c(0, 1000)), aes(x)) + 
  stat_function(fun = dnorm, geom = "density", args = list(mean = 200, sd = 50), 
                aes(color="technology", fill="technology", alpha= 0.75)) + 
  stat_function(fun = dnorm, geom = "density", args = list(mean = 500, sd = 200), 
                aes(color="textiles", fill="textiles", alpha = 0.75)) +
  stat_function(fun = dnorm, geom = "density", args = list(mean = 750, sd = 100), 
                aes(color="pharmaceuticals", fill="pharmaceuticals", alpha = 0.75)) + 
  labs(list(title="Fictious 'Density' Returns by Industry", x=NULL, y=NULL, color="Industry")) +
  theme(legend.position="none") +
  theme(axis.ticks = element_blank(), axis.text.y = element_blank()) +
  annotate("text", label="technology", x=275, y=0.008, color="green4") +
  annotate("text", label="textiles", x=500, y=0.0025, color="blue4") +
  annotate("text", label="pharmaceuticals", x=835, y=0.0045, color="red4")

1 个答案:

答案 0 :(得分:4)

使用ggplot_build,查看幕后发生的事情:

 unique(sapply(ggplot_build(p)$data,'[[','colour'))
   [,1]      [,2]      [,3]     
[1,] "#00BA38" "#619CFF" "#F8766D"

 unique(sapply(ggplot_build(p)$data,'[[','fill'))
     [,1]      [,2]      [,3]     
[1,] "#00BA38" "#619CFF" "#F8766D"