【问题标题】:Stitch facets in ggplotggplot中的缝合面
【发布时间】:2016-12-13 02:21:29
【问题描述】:

我有 2 个数据集我想并排 ggplot,以便它们共享 y-axis

我曾想过为此使用ggplotfacet_wrap,但我想知道如何将它们一起stitch。这是我目前所拥有的:

df.1 <- data.frame(x=c(-0.678071905112638,1.32192809488736,-0.678071905112638,1.32192809488736,-0.678071905112638,1.32192809488736),
                   y=c(62.8805462356349,73.027603062927,88.4090942806369,87.6879626013305,55.9895740872068,93.5396099910227),
                   side=1,stringsAsFactors = F)

df.2 <- data.frame(x=c(1.32192809488736,3.32192809488736,1.32192809488736,1.32192809488736),
                   y=c(73.027603062927,7.33717302418609,87.6879626013305,93.5396099910227),
                   side=2,stringsAsFactors = F)

df <- rbind(df.1,df.2)
df$side <- factor(df$side,levels=c(1,2))

require(ggplot2)
ggplot(df,aes(x=x,y=y))+geom_point()+facet_wrap(~side,ncol=2,scales="free")+stat_smooth(method="lm",formula=y~x,colour="black")+theme(strip.text.y=element_text())

如何摆脱右侧刻面的 y 轴并移除刻面之间的空间,使它们显示为单个图形?此外,它们需要具有相同的 y 轴坐标。

需要明确的是,我使用两个 facets 的原因是因为我分别为每个 df 安装了一个 lm。

【问题讨论】:

    标签: r ggplot2 facet


    【解决方案1】:

    您可以调整构面之间的边距以删除空间。此外,使用scales="free_x" 以便只有 x 轴刻度是空闲的,而 y 轴刻度是相同的。因为每个切面的 y 轴刻度都相同,所以不会在右侧切面重复刻度:

    theme_set(cowplot::theme_cowplot()) 
    
    ggplot(df,aes(x=x,y=y))+geom_point() + 
      facet_wrap(~side, ncol=2, scales="free_x") + 
      stat_smooth(method="lm", formula=y~x, colour="black") + 
      theme(panel.spacing = unit(-1.25, "lines")) 
    

    但您也可以避免刻面并使用颜色美学获得单独的线条。这种方法将所有内容都放在一个面板上,因此您不必担心在构面之间排列 x 尺度:

    ggplot(df,aes(x=x, y=y)) + 
      geom_point() + 
      stat_smooth(method="lm",formula=y~x, aes(colour=side))
    

    【讨论】:

      【解决方案2】:

      使用ylim 设置y 限制。使用panel.spacing.x 调整间隙。用axis.text.y 去掉不需要的标签,用axis.ticks 去掉勾号。

      ggplot(df,aes(x=x,y=y))+geom_point()+ ylim(0, 120) +
               facet_wrap(~side,ncol=2,scales="free")+
              stat_smooth(method="lm",formula=y~x,colour="black")+
              theme(strip.text.y=element_text(),  axis.text.y = element_blank(),
            axis.ticks = element_blank(), panel.spacing.x=unit(0, "lines"))
      

      【讨论】:

        猜你喜欢
        • 2013-09-22
        • 1970-01-01
        • 1970-01-01
        • 2020-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-25
        相关资源
        最近更新 更多