簡體   English   中英

使用ggplot2函數stat_smooth時遇到問題

[英]Having trouble using ggplot2 function stat_smooth

我有以下數據:

#means and SEs
s2humanlikem<-c(1.895,1.658,2.684,2.421,2.921,2.158,3.632,2.737,4.526,4.105)
s2humanlikese<-c(.199,.157,.250,.234,.243,.225,.197,.235,.145,.180)
s2agent<-c("Software","Software","Machine","Machine","Robot","Robot","Android","Android","Human","Human")
Story<-c("Cooperative","Self-interested")

#combine into dataframe
hri2<-data.frame(s2agent,s2humanlikem,s2humanlikese,Story)

#make numeric and factor
hri2$s2agent <- factor(hri2$s2agent, levels = c("Software","Machine", "Robot", "Android","Human"))
hri2$s2humanlikem<-as.numeric(levels(hri2$s2humanlikem))[hri2$s2humanlikem]
hri2$s2humanlikese<-as.numeric(levels(hri2$s2humanlikese))[hri2$s2humanlikese]

我正在嘗試使用以下代碼進行繪制:

ggplot(hri2,aes(x=s2agent,y=s2humanlikem,group=Story)) +
  stat_smooth(aes(x=seq(length((s2agent)))),se=F,method="lm",formula=y~poly(x,4)) +
  scale_x_continuous(breaks=seq(length(unique(hri2$s2agent))),labels=levels(hri2$s2agent))

但是,如您所見,圖形的軸是不固定的。 由於某些原因,這兩行也未對齊,我不知道為什么。 任何幫助,將不勝感激。

感謝您的關注!

x轉換為數字並刪除stat_smoothseq可得到所需的結果:

ggplot(hri2,aes(x=as.numeric(s2agent),y=s2humanlikem,group=Story)) +
  stat_smooth(se=FALSE,method="lm",formula=y~poly(x,4)) +
  scale_x_continuous(breaks=seq(length(unique(hri2$s2agent))),labels=levels(hri2$s2agent))

結果如下圖: 在此處輸入圖片說明


更新:如果要在圖中包括SE,則必須從原始數據幀中進行繪圖,並從中計算出meanse

如果要使用提供的數據,例如,可以使用以下內容:

ggplot(hri2,aes(x=s2agent,y=s2humanlikem,group=Story)) +
  geom_line(color="blue",size=1) +
  geom_ribbon(aes(ymin=s2humanlikem-s2humanlikese, ymax=s2humanlikem+s2humanlikese), alpha=0.3) +
  scale_x_discrete(expand=c(0,0)) +
  theme_bw()

這給出了: 在此處輸入圖片說明

暫無
暫無

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

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