R 确定ggplot2打印区域的宽度
我尝试使用gridExtra组合两个ggplot2条形图(坐标翻转,以便标签占据水平空间)。问题是有些标签很短,有些标签很长。我希望左右列的宽度相同,而与标签的宽度无关。下面是一个例子:R 确定ggplot2打印区域的宽度,r,ggplot2,R,Ggplot2,我尝试使用gridExtra组合两个ggplot2条形图(坐标翻转,以便标签占据水平空间)。问题是有些标签很短,有些标签很长。我希望左右列的宽度相同,而与标签的宽度无关。下面是一个例子: library(ggplot2) library(gridExtra) datashort <- data.frame(ecks = c("Short1", "Short2", "Short3"), why = c(30, 20, 40)) datalong <- data.frame(ecks
library(ggplot2)
library(gridExtra)
datashort <- data.frame(ecks = c("Short1", "Short2", "Short3"), why = c(30, 20, 40))
datalong <- data.frame(ecks = c(paste0("Really, Really, Really, Really Long", c(1:3))),
why = c(20, 30, 40))
plotshort <- ggplot(data = datashort, aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") +
scale_y_continuous(breaks = c(10, 20, 30, 40, 50), limits = c(0, 50)) +
coord_flip()
plotlong <- ggplot(data = datalong, aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") +
scale_y_continuous(breaks = c(10, 20, 30, 40, 50), limits = c(0, 50)) +
coord_flip()
grid.arrange(plotshort, plotlong, ncol = 2)
库(ggplot2)
图书馆(gridExtra)
datashort一个非常简单的解决方案是使用cowplot
:
cowplot::plot_grid(plotshort, plotlong, ncol = 2,align = "v")
参数align
允许您将打印区域设置为相等
或者,另一种选择是在标题中添加一些分隔符:
library(stringr)
plotlong <- datalong %>%
mutate(ecks = str_replace_all(ecks, "[[:punct:]]\\s|\\s", "\\\n")) %>%
ggplot(aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") +
scale_y_continuous(breaks = c(10, 20, 30, 40, 50), limits = c(0, 50)) +
coord_flip()
cowplot::plot_grid(plotshort, plotlong, ncol = 2,align = "v")
您可以使用stringr
包装标签,并修改ggplot2
脚本以在st\u wrap
中定义标签,并以scale\u x\u discrete
方式打印:
library(stringr)
plotshort <- ggplot(data = datashort, aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") + coord_flip() +
scale_x_discrete(labels = str_wrap(c("Short1", "Short2", "Short3"), width = 10))
plotlong <- ggplot(data = datalong, aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") + coord_flip() +
scale_x_discrete(labels = str_wrap(c("Really, Really, Really, Really Long1", "Really, Really, Really, Really Long2", "Really, Really, Really, Really Long3"), width = 10))
grid.arrange(plotshort, plotlong, ncol = 2)
库(stringr)
plotshort您可以使用egg::ggarrange
查看此帖子:。另外,如果在生成绘图之前将标签分成多行,可能会有所帮助:datalong$ecks这对这些数据很有效,但我正在处理的实际数据约有70行,因此包装它们并不方便。另外,这仍然不能使绘图区域大小相等,它只是避免了一些挤压。我将使用cowplot解决方案。谢谢
library(stringr)
plotshort <- ggplot(data = datashort, aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") + coord_flip() +
scale_x_discrete(labels = str_wrap(c("Short1", "Short2", "Short3"), width = 10))
plotlong <- ggplot(data = datalong, aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") + coord_flip() +
scale_x_discrete(labels = str_wrap(c("Really, Really, Really, Really Long1", "Really, Really, Really, Really Long2", "Really, Really, Really, Really Long3"), width = 10))
grid.arrange(plotshort, plotlong, ncol = 2)