簡體   English   中英

ggplot-在帶有裝箱(非連續)x軸的箱線圖上添加回歸線

[英]ggplot - Add regression line on a boxplot with binned (non-continuous) x-axis

我有一個具有以下結構的數據集:

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的解決方案是什么? 謝謝

可以按照您的要求進行操作,但這是一個令人震驚的壞主意。

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)返回因子代碼。 如果您的垃圾箱大小不盡相同(就您而言,它們大小也不相同),則該圖可能會產生誤導。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM