【问题标题】:ggplot - Add regression line on a boxplot with binned (non-continuous) x-axisggplot - 在带有分箱(非连续)x 轴的箱线图上添加回归线
【发布时间】:2014-12-30 05:19:23
【问题描述】:

我有一个具有这种结构的数据集:

df<- data.frame (VPD.mean=rnorm(100,mean=2,sd=0.8), treatment=c("ambient","elevated"), variable=rnorm(100,mean=50,sd=10))
df$group <- with(df, as.factor (ifelse (VPD.mean>0 & VPD.mean<=1,"0-1",ifelse (
  VPD.mean>1 & VPD.mean<=1.5,"1-1.5",ifelse (
    VPD.mean >1.5 & VPD.mean<2, "1.5-2",ifelse (
      VPD.mean >=2 & VPD.mean<2.5, "2-2.5",ifelse (
        VPD.mean >=2.5 & VPD.mean <3,"2.5-3", ifelse(
          VPD.mean >=3,">3", NA)  
      )))))))
df$group<- factor(df$group,levels=c("0-1","1-1.5","1.5-2" ,"2-2.5","2.5-3",">3"))

我使用分箱 VPD.mean 后创建的组创建了箱线图,因此 x 轴是不连续的(见下图):

我还想添加一条回归线(平滑),因此我必须使用连续变量 (VPD.mean) 而不是合并的一个(组)作为 x 轴。结果并不好,因为平滑线与图形的 x 轴不匹配。这是ggplot的代码:

ggplot(df[!is.na(df$group),], aes(group,variable,fill=treatment)) + 
  geom_boxplot(outlier.size = 0) + geom_smooth(aes(x=VPD.mean)) 

在同一张图上从不同的 x 轴绘制 geom_smooth 的解决方案是什么? 谢谢

【问题讨论】:

  • 在我看来,将这两种不同类型的图绘制成一个图(如果可能的话)是不明智的。你的情节看起来很混乱。因此,最好制作两个单独的图。

标签: r ggplot2 boxplot


【解决方案1】:

可以按照你的要求去做,但这是一个非常糟糕的主意。

set.seed(1)  # for reproducible example
df<- data.frame (VPD.mean=rnorm(100,mean=2,sd=0.8), treatment=c("ambient","elevated"), variable=rnorm(100,mean=50,sd=10))
df$group <- cut(df$VPD.mean,
                breaks=c(0,seq(1,3,by=0.5),Inf), 
                labels=c("0-1","1-1.5","1.5-2","2-2.5","2.5-3",">3"))
library(ggplot2)
ggplot(df[!is.na(df$group),]) +
  geom_boxplot(aes(x=factor(group),y=variable,fill=treatment),
               position=position_dodge(.7),width=.8)+
  geom_smooth(aes(x=as.integer(group),y=variable,color=treatment,fill=treatment),method=loess)

这或多或少是有效的,因为ggplot 使用 x 轴的因子代码和轴标签的因子水平。 as.integer(group) 返回因子代码。如果您的垃圾箱大小不同(在您的情况下它们不是),则该图可能会产生误导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2017-12-19
    • 2022-08-18
    • 2016-09-16
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多