在R中通过annotate使用ggplot2图表的默认填充颜色

3
我想获取ggplot2中的默认线条或填充颜色,但我不确定该如何做。具体来说,在下面的代码中,你会看到green4blue4red4被用在注释中。这些是我认为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个回答

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"

谢谢 - 实际上我不得不添加另一个sapply( ... , unique)来避免获取每个列表标签的所有101个元素。 - JasonAizkalns

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接