[英]Overlap measurement points on a grouped geom_boxplot() using ggplot2
[英]Manually define size of frame using ggplot2 and geom_boxplot
使用ggplot2绘制多个箱形图时,如何手动定义单个图形的框架大小?
例如,如果您有一个2x2的图,并且每个帧都应该是具有400x400像素高度和宽度的二次方,则由于轴文本仍然存在(因此长度可能会有所不同,因此您无法将整个图的尺寸设置为800x800) facet_wrap(〜variable,scales =“ free_y”))中的“ scales =” free_y“命令。这会导致”压缩“,而不是二次帧大小。
p<-ggplot(data=data.frame,aes(x=x,y=value))+
geom_boxplot(size=0.1, fill="grey90")+
geom_point(aes(x=x, y=value, fill="black"),inherit.aes=FALSE, colour="red", size=2, position=position_jitterdodge(jitter.width = 0.25), show.legend=FALSE)+
facet_wrap(~variable,scales="free_y")+
theme_bw()
预期结果:图形框应始终为二次方,且高度和宽度由用户定义。
您可以通过以下方式对gtables执行此操作。 首先,我们将构建一个情节。
library(ggplot2)
library(grid)
# I don't have your data so I'll just use the diamonds dataset
p <- ggplot(diamonds, aes(x = cut, y = price)) +
geom_boxplot() +
facet_wrap(~ clarity, scales = "free_y")
然后,将图转换为gtable,获取面板位置并根据自己的喜好调整宽度和高度。
gt <- ggplotGrob(p)
# Usually panels don't span multiple cells in the table, so we can take the
# left ("l") and top ("t") positions of the panels.
panel_x <- panel_cols(gt)[,"l"]
panel_y <- panel_rows(gt)[,"t"]
gt$widths[panel_x] <- unit(400/72, "inches")
gt$heights[panel_y] <- unit(400/72, "inches")
grid.newpage(); grid.draw(gt)
不幸的是unit()
函数不允许您以像素为单位指定尺寸,因此我假设您的输出分辨率为每英寸72像素。 看一下?unit
查看选项。
编辑:
这是上面的样子(为简便起见unit(100/72, "inches")
使用unit(100/72, "inches")
):
现在,如果您还希望将条带(在深色框中看起来像面板标题的文本)包含在400x400框中,则可能需要查找行中的条带位置,并将其从提供的单位中减去。
gt <- ggplotGrob(p)
panel_x <- panel_cols(gt)[,"l"]
panel_y <- panel_rows(gt)[,"t"]
strip_y <- unique(gt$layout$t[grepl("strip", gt$layout$name)])
gt$widths[panel_x] <- unit(100/72, "inches")
gt$heights[panel_y] <- unit(100/72, "inches") - gt$heights[strip_y]
grid.newpage(); grid.draw(gt)
如下所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.