gpt4 book ai didi

r - ggplot2 - 多图缩放

转载 作者:行者123 更新时间:2023-12-04 02:09:19 27 4
gpt4 key购买 nike

我试图用 ggplot2 生成多个网格图。所以我想生成分布图,在 x 轴下方带有额外的箱线图,以及针对不同组和变量的分布图,例如:

Example

代码:我尝试使用以下代码来做到这一点:

library(ggplot2)
require(grid)

x=rbind(data.frame(D1=rnorm(1000),Name="titi",ID=c(1:1000)),
data.frame(D1=rnorm(1000)+1,Name="toto",ID=c(1:1000)))

space=1
suite=1
p1=ggplot(x, aes(x=D1, color=Name, fill=Name)) +
geom_histogram(aes(y=..density..),alpha=0.35,color=adjustcolor("white",0),position="identity",binwidth = 0.05)+
geom_density(alpha=.2,size=1)+
theme_minimal()+
labs(x=NULL,y="Density")+
theme(legend.position = "top",
legend.title = element_blank())+
scale_fill_manual(values=c("gray30","royalblue1"))+
scale_color_manual(values=c("gray30","royalblue1"))

p2=ggplot(x, aes(x=factor(Name), y=D1,fill=factor(Name),color=factor(Name)))+
geom_boxplot(alpha=0.2)+
theme_minimal()+
coord_flip()+
labs(x=NULL,y=NULL)+
theme(legend.position = "none",
axis.text.y = element_blank(),
axis.text.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.y = element_blank())+
scale_fill_manual(values=c("gray30","royalblue1"))+
scale_color_manual(values=c("gray30","royalblue1"))

grid.newpage()
pushViewport(viewport(layout=grid.layout(5,1)))
define_region <- function(row, col){
viewport(layout.pos.row = row, layout.pos.col = col)
}
print(p1, vp=define_region(1:4,1))
print(p2, vp=define_region(5,1))

结果:

enter image description here

问题:在我的搜索过程中,我观察到密度分布图和箱线图之间的比例不同(问题 1)。我还没有找到在网格中绘制这两个图形的解决方案(我迷路了)。

最佳答案

cowplot打包这会变得更容易一些。但是,我们应该正确设置 x 轴范围以确保它们对于两个图是相同的。这是因为密度图自然比纯数据图宽一点,而 p1 的轴因此会更宽一些。当轴固定后,我们可以排列和对齐它们(轴文本和边距将不再重要)。

library(cowplot)
comb <- plot_grid(
p1 + xlim(-5, 5),
p2 + ylim(-5, 5), # use ylim for p2 because of coord_flip()
align = 'v', rel_heights = c(4, 1), nrow = 2
)

enter image description here

类似地,我们可以排列多个组合图:
plot_grid(comb, comb, comb, comb)

enter image description here

关于r - ggplot2 - 多图缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42220917/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com