不同的x和y轴在多面散射ggplot2中缩放

时间:2017-05-30 08:47:16

标签: r ggplot2

我用过" easyGgplot2"使用以下代码

绘制具有回归和置信区间线的多面(2个数字)散点图
ggplot2.scatterplot(data=data_calibration, xName='Observed', yName="Predicted",
                    size=1, addRegLine=TRUE, regLineColor="black",
                    addConfidenceInterval=TRUE,removePanelGrid=TRUE,
                    backgroundColor="white",xtitle="Observed Yield (kg/ha)", ytitle="Predicted Yield (kg/ha)",
                    removePanelGrid=F,removePanelBorder=F,
                    faceting=TRUE, facetingVarNames=c("Station", "Method"),
                    facetingScales="free")

我希望x和y轴刻度都是自由的。但我只是获得自由的y轴刻度。 enter image description here 我无法添加数据集,因为它是一个大矩阵。 在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

this post的帮助下,我已经解决了这个问题。

首先,使用facet_gridfacet_wrap创建两个图。

g1 = ggplot(data_calibration, aes(Observed,Predicted))+
  geom_point(color="black",alpha = 1/3) + 
  facet_wrap(Station ~ Method, scales="free", ncol=6)+
  xlab("Measured") +
  ylab("Predicted")+ theme_bw()+
  geom_smooth(method="lm")+
  theme(strip.background = element_blank(),
        strip.text = element_blank())

g2 = ggplot(data_calibration, aes(Observed,Predicted))+
  geom_point(color="black",alpha = 1/3) + 
  facet_grid(Station ~ Method, scales="free")+
  xlab("Measured") +
  ylab("Predicted")+ theme_bw()+
  geom_smooth(method="lm")

现在将g1的顶部小条替换为g2的顶部小条

library(grid)
library(gtable) 
gt1 = ggplot_gtable(ggplot_build(g1))
gt2 = ggplot_gtable(ggplot_build(g2))
gt1$grobs[grep('strip-t.+1$', gt1$layout$name)] = gt2$grobs[grep('strip-t', gt2$layout$name)]
grid.draw(gt1)

enter image description here

添加右侧面板条

gt1 = gtable_add_cols(gt1, widths=gt1$widths[1], pos = -1)

panel_id <- gt1$layout[grep('panel-.+1$', gt1$layout$name),]
gt.side1 = gtable_filter(gt2, 'strip-r-1')
gt.side2 = gtable_filter(gt2, 'strip-r-2')
gt.side3 = gtable_filter(gt2, 'strip-r-3')
gt1 = gtable_add_grob(gt1, zeroGrob(), t = 1, l = ncol(gt1), b=nrow(gt1))
gt1 = gtable_add_grob(gt1, gt.side1, t = panel_id$t[1], l = ncol(gt1))
gt1 = gtable_add_grob(gt1, gt.side2, t = panel_id$t[2], l = ncol(gt1))
gt1 = gtable_add_grob(gt1, gt.side3, t = panel_id$t[3], l = ncol(gt1))

grid.newpage()
grid.draw(gt1)

enter image description here