尝试使grid.arrange&rangeGrob中的曲线底部平整。也尝试移动Y轴标签

时间:2019-06-13 16:55:08

标签: r ggplot2 plot histogram

picture of plots

我有3个地块,其中两个地块彼此叠放在一起,作为一个地块出现。我制作了一个并排(2列)的图,因此看起来像是两个并排的图(尽管同样,一个图实际上是两个图的叠加)。我有两个问题:

  1. 无论我尝试什么(调整,缩放等),我都无法使两个并排图的底部保持一致。

  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)

1 个答案:

答案 0 :(得分:2)

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

要从github安装软件包:

devtools::install_github("thomasp85/patchwork")

然后

library(patchwork)

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

enter image description here