【问题标题】:ggplot2 facet marginggplot2构面边距
【发布时间】:2012-10-02 14:34:47
【问题描述】:

我使用facet_wrap 来绘制一些数据。这是一个例子:

library (ggplot2)
library (reshape)

# generate some dummy data
x = seq(0,1,0.05)
precision = sqrt(x)
recall    = 1 - precision
fmeasure  = 2 * (precision * recall) / (precision + recall)

# prepare it for plotting
df = data.frame(x=x, precision=precision, recall=recall, fmeasure=fmeasure)
df = melt(df, id.vars=c(x))

# plot it
p = ggplot(df, aes(x=x, y=value, group=variable))
p = p + geom_line() + facet_wrap(~variable, ncol=3)
p = p + coord_cartesian(xlim=c(0,1), ylim=c(0,1)) # second plot is without this line
print (p)

图 1:以上代码的绘图。

但是,您在图 1 中看到的是后续分面的第一个和最后一个标签重叠。这可以通过增加刻面之间的空间来解决。其他选项是删除 xlimylim 范围,如图 2 所示,但这会在构面本身中保留不必要的空间。

图 2:删除线 p = p + coord_cartesian(xlim=c(0,1), ylim=c(0,1)) 的绘图。

我试图增加刻面之间的空间,但到目前为止我一直无法做到。你有什么建议吗?

我使用 ggplot2 0.9.1 版。

【问题讨论】:

  • 对于 0.9.1 使用:p + opts(panel.margin = unit(2, "lines")) 但你有很多额外的空白,而且 IMO 失去了刻面的效果(注意 0.9.2 现在使用 theme 而不是 @987654330 @)
  • 我把它作为答案扔掉了。不确定那是不是你想要的。
  • @Tyler Rinker。是的,这就是我一直在寻找的答案。谢谢!

标签: r ggplot2


【解决方案1】:

对于 0.9.1 使用:p + opts(panel.margin = unit(2, "lines")),但您有很多额外的空白,并且 IMO 失去了刻面的一些效果(注意 0.9.2 现在使用 theme 而不是 opts

多年来,ggplot2 API 发生了变化,截至 2018-02-01,这是更新的解决方案:

p + theme(panel.spacing = unit(2, "lines"))

【讨论】:

  • panel.margin 已弃用 (2.2.1),用于 panel.spacing
【解决方案2】:

根据 Tyler 的回答,您可以使用 strip.text 主题参数进一步将构面面板挤压在一起,如下所示:

library(tidyverse)

mpgTidy <- pivot_longer(mpg, c(cty, hwy), names_to="mpg_categ", values_to="mpg")

g <- ggplot(mpgTidy, aes(x=displ, y=mpg, color=factor(cyl))) +
  facet_wrap(~ mpg_categ) +
  geom_point()

g

g + theme(strip.text=element_text(margin=margin()),
          panel.spacing=unit(0, "lines"))

这在分面标签很长或包含换行符并且分面图既有行又有列时很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多