【问题标题】:Include guide() in ggplot2 theme在 ggplot2 主题中包含 guide()
【发布时间】:2020-12-23 18:47:39
【问题描述】:

我们的组织有一本非常严格的风格书,所以我的任务是创建一个 ggplot 主题,程序员可以使用它来确保他们的图表和图形尽可能接近“官方”风格。

其中一个要求是图表的图例在图表下方,但垂直堆叠,如下所示:

我一直在通过以下方式生成这样的图形:

pie_theme <- theme(
    text = element_text(family = "Arial", face = "bold", size = 7, color = "black"),
    plot.caption = element_text(hjust = 0, size = 6),
    legend.position = "bottom",
    etc.
    )
    
    p1 <- ggplot(bla bla bla)+geom_bar(bla bla bla)+coord_polar(bla bla bla)
    
    p1+ guides(fill=guide_legend(ncol=1)) +
      pie_theme

理想情况下,我想将guides() 命令集成到主题中,这样程序员就不必每次输出图表时都添加guides(),并且图例会自动垂直堆叠。但我没有看到可以做到这一点的 theme() 属性。有什么建议吗?

谢谢!

【问题讨论】:

    标签: r ggplot2 themes customization legend


    【解决方案1】:

    ggplot 对象和列表的+ 操作可以将列表的每个元素单独添加到绘图中。为此,您可以将主题和指南包装在一个列表中,然后您可以像添加常规主题一样添加它。

    提醒一句,如果您将连续变量映射到指南,它将尝试选择 guide_legend() 而不是 guide_colorbar(),如果您以这种方式使用它,这可能更合适。

    library(ggplot2)
    
    pie_theme <- list(
      theme(
        text = element_text(face = "bold", size = 7, color = "black"),
        plot.caption = element_text(hjust = 0, size = 6),
        legend.position = "bottom"
      ),
      guides(fill = guide_legend(ncol = 1))
    )
    
    ggplot(mtcars, aes(x = factor(1), fill = factor(cyl))) +
      geom_bar(width = 1) +
      coord_polar(theta = "y") +
      pie_theme
    

    由reprex package (v0.3.0) 于 2020 年 12 月 23 日创建

    【讨论】:

    • 问题的可能扩展:是否可以使用函数(而不是预定义的pie_theme)仅添加指南/主题/...如果之前未设置?例如,如果你的ggplot(...) + geom_bar(...) + coord_polar(...) + themes(legend.position="top") + pie_theme(),它不会尝试复制之前分配的主题值?
    • 好吧,使用... + pie_theme + theme(legend.position = "top") 可能比反过来更容易。我想你可以编写一个自定义主题类,使用它自己的 ggplot_add() 方法来检查这个,但是这将比仅仅切换操作顺序更复杂。
    • 我就是这么想的。我正在想象一种通用方式,其中包括 scale_*_* 中包含的内容,以抑制 ggplot2 使用重复调用/参数引发的注释/警告。谢谢。
    • 我记得我在这里回答了关于条件主题设置的类似问题:stackoverflow.com/questions/58149562/…
    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 2023-04-05
    • 1970-01-01
    • 2014-02-10
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多