我在 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])
Run Code Online (Sandbox Code Playgroud)
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] ) )
Run Code Online (Sandbox Code Playgroud)
我的目标是 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)
Run Code Online (Sandbox Code Playgroud)
即使图例不同,我生成的每个 PNG 中的图形也应具有相同的大小。
非常感谢!
将图例放在右侧,为每个图例项提供行数,然后根据需要垂直排列图会更容易。
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)
Run Code Online (Sandbox Code Playgroud)
编辑:如果您仍然想要底部的图例,请改用以下内容(但在我看来,正确的图例格式在视觉上更具吸引力)。
gA = ggplotGrob(g1)
gB = ggplotGrob(g2)
gB$heights <- gA$heights
grid.arrange(gA, gB)
Run Code Online (Sandbox Code Playgroud)