首页 文章

修复了ggplot2中的图形大小

提问于
浏览
4

我在R中的ggplot2包有些麻烦 . 我有很多具有类似结构的数据,并且想要绘制它 . 所以我认为我可以编写一个函数并在循环中使用它 . 问题是不同的布局 . 在下面的示例中,df1包含坐标(x和y)和值 .

df1 <- data.frame(x_coord = c(1:100,1:100), y_coord = c(100:1, 1:100),
                  value = LETTERS[1:10])

Df2几乎相同,但值名称较长:

df2 <- data.frame(x_coord = c(1:100,1:100), y_coord = c(100:1, 1:100),
                  value = paste0("longer_legend_entry_" ,LETTERS[1:10] ) )

我的目标是ggplot具有相同大小的df1和df2的图形 . 所以我使用coord_fixed()来保持宽高比 . 但是,由于我必须告诉ggsave()将图形保存为PNG时的大小(以英寸为单位),不同大小的图例会导致问题 .

ggplot(data = df1, aes( x = x_coord, y = y_coord, color = value ) ) +
  geom_point() +
  theme( legend.position="bottom" ) +
  coord_fixed()

ggsave("plot1.png", width=3, height=3, dpi=100)

ggplot(data = df2, aes( x = x_coord, y = y_coord, color = value ) ) +
  geom_point() +
  theme( legend.position="bottom" ) +
  coord_fixed()

ggsave("plot2.png", width=3, height=3, dpi=100)

plot1

plot2

即使图例不同,图表也应该在我生成的每个PNG中具有相同的大小 .

非常感谢!

1 回答

  • 1

    将图例放在右侧会更容易,为每个图例项提供行数,然后根据需要垂直排列图 .

    library(gridExtra)
    g1 = ggplot(data = df1, aes(x = x_coord, y = y_coord, color = value)) +
      geom_point() +
      theme(legend.position="right") +
      coord_fixed() + guides(col = guide_legend(nrow = 2))
    
    g2 = ggplot(data = df2, aes( x = x_coord, y = y_coord, color = value ) ) +
      geom_point() +
      theme( legend.position="right" ) +
      coord_fixed() + guides(col = guide_legend(nrow = 5))
    
    gA = ggplotGrob(g1)
    gB = ggplotGrob(g2)
    gA$widths <- gB$widths
    grid.arrange(gA, gB)
    

    enter image description here

    Edit: 如果您仍然想要底部的图例,请使用以下内容(但在我看来,正确的图例格式在视觉上更具吸引力) .

    gA = ggplotGrob(g1)
    gB = ggplotGrob(g2)
    gB$heights <- gA$heights
    grid.arrange(gA, gB)
    

相关问题