【问题标题】:Dropping y strip, but not x, from ggplot2 facet从 ggplot2 方面删除 y 条,但不删除 x
【发布时间】:2014-10-06 21:44:26
【问题描述】:

我正在使用 ggplot2 创建 2D 刻面图。我希望删除 y 轴条(因为它是不言自明的)但删除 x 轴条(因为它不是)。

我发现了几个关于如何删除两个条带的示例,例如this。但是,在每种情况下,它都在向您展示如何摆脱所有标签。有一个how to remove the labels from one panel and not the other 的例子,但这似乎比我想象的要复杂(希望)它实际上是。 (另外,当我复制和粘贴代码时,R 无法识别出现在代码片段中的“单元”命令,尽管I see that this is addressed elsewhere。)

所以,假设我有下面的分面网格,我想隐藏 cut 的灰色条,而不是 color

require(ggplot2)
pdf(file = sprintf("minimal.pdf"))
p <- ggplot(diamonds, aes(carat, price))
p <- p + geom_point()
p <- p + facet_grid(cut ~ color, scales="fixed")
print(p)
dev.off()

添加以下行会将两个条带变为白色,并从 y 条带中删除字符(剪切)。

p <- p + theme(strip.text.y = element_blank(), strip.background = element_blank())

这是一个改进,但我真正想做的是保持 x-strip 原样,使用原始的灰色背景,但删除 y-strip。每次调整图形大小时手动调整边距,就像在其中一个参考文献中所做的那样,这似乎不是一个好方法。我想知道是否有更好的方法。

【问题讨论】:

  • 你能用假数据重现这个吗?
  • 我不认为添加+theme(strip.text.y = element_blank(), strip.background = element_blank())有那么复杂......无论如何如果你经常使用它,你可以像my.theme &lt;- theme(strip.text.y = element_blank(), strip.background = element_blank())一样保存它然后你所要做的就是p + my.theme
  • Maloneypatr,已按要求编辑以使用可重现的数据。 Konvas,我同意这并不复杂,但它并没有做正确的事情(见编辑过的问题)。

标签: r plot ggplot2


【解决方案1】:

您可以对 gtable 进行子集化以删除您不想要的列

g <- ggplotGrob(p)

strips <- subset(g$layout, grepl("strip-right", g$layout$name))

library(grid)
grid.newpage()
grid.draw(g[,-unique(strips$r)])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2012-10-05
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多