【问题标题】:Fixed graph size in ggplot2固定 ggplot2 中的图形大小
【发布时间】:2023-03-28 15:25:02
【问题描述】:

我在使用 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() 来保持纵横比。但是由于在将绘图保存为 PNG 时我必须告诉 ggsave() 以英寸为单位的大小,所以图例的不同大小会导致问题。

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)

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

非常感谢!

【问题讨论】:

标签: r ggplot2


【解决方案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)

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

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

【讨论】:

    猜你喜欢
    • 2016-08-28
    • 1970-01-01
    • 2012-11-12
    • 2019-04-06
    • 2021-11-24
    • 2017-12-12
    • 2019-01-07
    • 1970-01-01
    • 2016-03-13
    相关资源
    最近更新 更多