首页 > 解决方案 > 试图在 grid.arrange 和arrangeGrob 中平衡地块的底部。还试图移动 Y 轴标签

问题描述

地块的图片

我有 3 个地块,两个地块堆叠在一起,显示为一个地块。我做了一个并排(2 列)的图,所以它看起来像 2 个地块彼此相邻(尽管同样,一个地块实际上是两个地块堆叠在一起)。我有两个问题:

  1. 无论我尝试什么(vjust、缩放等),我都无法让两个并排的图的底部保持平衡。

  2. 我无法获得以堆叠图为中心的 Y 轴标签,因为您无法制作跨越两个图的标签。我已经尝试对整个面板使用“标题”,但是我无法更改字体大小以匹配其余标签。

我尝试过使用 vjust,为整个情节添加标题,改用 plot_grid,以及我能想到的所有其他内容。

city<-c("A", "B", "A", "B", "A", "B")
temp<-c(20, 25, 300, 35, 30, 400)
data1<-data.frame(city, temp)

library(cowplot)
library(gridExtra)

g.top <- ggplot(data1[data1$variable == "city A", ], aes(x = temp)) 
+
geom_histogram(binwidth=1) +
scale_x_continuous(limits = c(0, 100), position = "top") +
scale_y_reverse(limits = c(400, 0))+
theme_minimal(base_size = 16) + theme(panel.grid.major = element_blank(), 
panel.grid.minor = element_blank(),
                      panel.background = element_blank(), axis.line = 
element_line(colour = "black"))+
annotate("text", x=20, y=200, cex=6, label= "city A")+ labs(title="a", 
y="Count")+theme(axis.title.x=element_blank())


g.bottom <- ggplot(data1[data1$variable == "city B", ], aes(x = 
temp)) +
geom_histogram(binwidth=1) +
scale_x_continuous(limits = c(0, 100)) + ylim(0, 400)+
theme_minimal(base_size = 16)+ theme(panel.grid.major = element_blank(), 
panel.grid.minor = element_blank(),
                      panel.background = element_blank(), axis.line = 
element_line(colour = "black"))+
annotate("text", x=20, y=200, cex=6, label= "city B") + labs(x = 
expression("Temp (F)"), y="") 

mean<-c(2, 6)
se<-c(0.01, 0.3)
city<-c("A","B")
df<-data.frame(mean, se, city)

gg<- ggplot(df, aes(x=city, y=mean, group=city, 
color=city, shape=city)) + 
geom_line(size=1, position=position_dodge(0.2))+
geom_jitter(aes(shape=city, size=city), alpha=1, 
position=position_dodge(0.2))+
geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.4, 
position=position_dodge(0.2))+
labs(title= "b", x= expression("City"), y =expression("Temp (F)"))+
theme_bw(base_size = 16) + theme(axis.title.x = 
element_text(vjust=200000000), axis.title.y = element_text(vjust=-7), 
legend.title=element_blank())+
theme(legend.justification=c(0.1,0.1), legend.position=c(0.6,0.1))+
scale_color_manual(values=c('#104E8BC8','#FF8C00C8'))+
scale_size_manual(values=c(4,4))+
scale_shape_manual(values=c(19, 17))+theme(legend.position="none")+
theme(axis.ticks.length=unit(-0.25, "cm"), axis.ticks.margin=unit(0.5, 
"cm"),axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5), 
"cm")),axis.text.y = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")))

grid.arrange(arrangeGrob(g.top, g.bottom), gg, ncol = 2)

标签: rggplot2plothistogram

解决方案


您可以使用该patchwork来布置图。有关布局系统如何工作的详细信息,请参阅 Vignette:

从 github 安装包:

devtools::install_github("thomasp85/patchwork")

然后,

library(patchwork)

{g.top + g.bottom + plot_layout(ncol=1)} - gg

在此处输入图像描述


推荐阅读