【问题标题】:How to get identical panel width with different y-axis text lengths如何使用不同的 y 轴文本长度获得相同的面板宽度
【发布时间】:2016-04-14 04:10:31
【问题描述】:

我正在通过一个循环绘制数百个图。每个图都有不同的参数,这导致 y 轴标签的范围从例如某些图中的 0.1-0.9 到其他图中的 100-1000。现在,当它们被绘制时,绘图的总大小保持不变,这意味着当 y 轴标签很长时,y 轴的位置向右移动,或者向左移动,当标签很短。

我想修复所有地块的面板宽度。本质上,如果标签很短,y 轴标题的左侧会有空白。

我的问题与此有些相似,但我对gtable 的了解不足,无法修改我想要的解决方案。 How achieve identical facet sizes and scales in several multi-facet ggplot2 graphics?

玩具示例:

df <- data.frame(x = c(rnorm(10, 0.1, 0.1), rnorm(10, 1000, 100)), 
y = c(rnorm(10, 0.1, 0.1), rnorm(10, 10000, 100)), 
name = c(rep(1, 10), rep(2, 10)))

for(i in 1:2){

p <- ggplot(df[df$name == i,]) +
    geom_point(aes(x = x, y = y))

filename <- paste("fig", i, ".jpg", sep = "")
jpeg(filename, width = 6.5, height = 5.5, units = "in", pointsize = 12, quality = 100, res = 500)
print(p)
dev.off()
    }

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用完整的数据集生成一个虚拟绘图“p”,将其转换为具有“g=ggplotGrob(p)”的 gtable,将其宽度存储为“w=g$widths”,并将每个绘图存储在循环将 gtable 的宽度替换为 'w'。

    p <- ggplot(df) +
      geom_point(aes(x = x, y = y))
    g <- ggplotGrob(p)
    w <- g$widths
    
    pdf("test.pdf")
    for(i in 1:2){
    
      p <- ggplot(df[df$name == i,]) +
        geom_point(aes(x = x, y = y))
      g <- ggplotGrob(p)
      g$widths <- w
      grid::grid.newpage()
      grid::grid.draw(g)
    }
    dev.off()
    

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 2015-11-27
      • 2020-06-21
      相关资源
      最近更新 更多