使用ggplot2函数stat_smooth时遇到问题

时间:2014-10-03 14:36:58

标签: r ggplot2

我有以下数据:

#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))

然而,正如您所看到的,图表的轴是不稳定的。由于某种原因,这两行也未对齐,我无法弄清楚原因。对此的任何帮助将不胜感激。

感谢您的关注!

1 个答案:

答案 0 :(得分:0)

x转换为数字并移除seq中的stat_smooth会得到所需的结果:

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))

这导致以下情节: enter image description here


更新:如果要在图表中包含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()

这给出了: enter image description here

相关问题