【问题标题】:ggplot theme: grid lines only with facetsggplot 主题:网格线仅带有刻面
【发布时间】:2017-03-02 08:09:54
【问题描述】:

我正在尝试为我制作的常见情节创建一个自定义的首选主题。在这些图中,我希望仅在图分面时才包含网格线。

例如,我在写了一些主题函数theme_my() 这样如果我写:

library(ggplot2)
theme_set(theme_my())
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class)

ggplot(mpg, aes(displ, hwy)) +
  geom_point()

结果是一样的

library(ggplot2)
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class)

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())

基本上,我想知道是否可以在我的主题函数中包含一些内容,以便在情节分面时模板使用最终的+theme(panel.grid.major ...) 调用。这可能吗?或者还有其他更好的方法吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我不确定是否将其自动化到主题中,但我依靠的一个解决方法是保存一组我想用于我所有构面图的 theme 名称,然后将其添加到情节调用。我倾向于将它用于panel.border,但这个想法对你来说应该是一样的。

    首先,设置一个没有网格线的主题:

    theme_set(theme_minimal() +
                theme(panel.grid.major = element_blank(),
                      panel.grid.minor = element_blank())
              )
    

    这将给出如下图:

    ggplot(mpg, aes(displ, hwy)) +
      geom_point()
    

    接下来,保存您要为facet 绘图设置的theme 选项组:

    facetSettings <-
      theme(panel.grid.major = element_line("lightgray",0.5),
            panel.grid.minor = element_line("lightgray",0.25))
    

    然后使用它:

    ggplot(mpg, aes(displ, hwy)) +
      geom_point() +
      facet_wrap(~class) +
      facetSettings
    

    这不如将它直接内置到主题中那么方便,但它确实有一些优势。如果您想在构面之外使用带有网格线的主题,您可以(例如,如果使用cowplot 构建您自己的多面板)。如果您决定在某个情况下您实际上需要特殊方面设置,则可以排除它们。最后,如果可以在实际主题中执行此操作,那么几乎肯定会比此处所需的代码更多。

    (也就是说,如果有人有办法做到这一点,我肯定很感兴趣,并且肯定我会找到一种方法来利用它。)

    【讨论】:

    • 这不是一个非常不方便的方法,而且绝对是一个合理的选择。不过让我们看看有没有其他建议!
    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2017-10-11
    • 2020-06-08
    相关资源
    最近更新 更多