gpt4 book ai didi

r - ggplot中对齐图的风险

转载 作者:行者123 更新时间:2023-12-03 14:51:22 26 4
gpt4 key购买 nike



如何合并具有不同y轴和不同绘图高度的单独绘图(ggplot2),又保持对齐?

详情

当使用grid.arrange(方法1)将图与具有不同y轴单位的图合并时,它们将不对齐。解决此问题的一种方法是使用gtable(method2),但是我无法调整绘图的相对高度。



require(ggplot2)

#Make two plots, with different y axis
x = c(1, 5)
y= c(.1, .4)
data1<-data.frame(x,y)
top<-
ggplot(data1, aes(x=x, y=y))+
geom_line()

x = c(1, 5)
y= c(100000, 400000)
data2<-data.frame(x,y)
bottom<-
ggplot(data2, aes(x=x, y=y))+
geom_line()


# Method 1 - Grid Extra
require(gridExtra)
grid.arrange(top, bottom, heights=c(.6,.3))


方法1导致此图,由于y轴标签的长度不同,该图未对齐:



#Method 2 - gtable
require(gtable)
#Extract Grobs
g1<-ggplotGrob(top)
g2<-ggplotGrob(bottom)
#Bind the tables
g<-gtable:::rbind_gtable(g1, g2, "first")
#Remove a row between the plots
g <- gtable_add_rows(g, unit(-1,"cm"), pos=nrow(g1))
#draw
grid.newpage()
grid.draw(g)


方法2导致对齐的图,但是我无法调整每个图的高度。


谢谢!

最佳答案

在gtable g中,您可以设置相对面板高度,

require(gtable)
g1<-ggplotGrob(top)
g2<-ggplotGrob(bottom)
g<-gtable:::rbind_gtable(g1, g2, "first")
panels <- g$layout$t[grep("panel", g$layout$name)]
g$heights[panels] <- unit(c(1,2), "null")

grid.newpage()
grid.draw(g)

关于r - ggplot中对齐图的风险,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24331107/

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