【问题标题】:Using default fill colors from ggplot2 graphs via annotate in R通过 R 中的注释使用 ggplot2 图形中的默认填充颜色
【发布时间】:2014-02-04 13:55:10
【问题描述】:

我想从 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")

【问题讨论】:

    标签: r graph colors ggplot2 visualization


    【解决方案1】:

    使用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 个元素。
    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2023-04-09
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多