[英]Having trouble using ggplot2 function stat_smooth
I have the following data: 我有以下数据:
#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]
that I'm trying to plot using the following code: 我正在尝试使用以下代码进行绘制:
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))
However as you can see, the graph's axes are wonky. 但是,如您所见,图形的轴是不固定的。 The two lines are also misaligned for some reason and I can't figure out why.
由于某些原因,这两行也未对齐,我不知道为什么。 Any help on this would be greatly appreciated.
任何帮助,将不胜感激。
Thanks for your attention! 感谢您的关注!
Converting you x
to numeric and removing the seq
in stat_smooth
gives the desired result: 将
x
转换为数字并删除stat_smooth
的seq
可得到所需的结果:
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))
this results in the following plot: 结果如下图:
UPDATE: When you want to include the SE in the plot, you will have to plot from the original dataframe from which you calculated the mean
and the se
. 更新:如果要在图中包括SE,则必须从原始数据帧中进行绘图,并从中计算出
mean
和se
。
If you want to use the data you provided, you could for example use the following: 如果要使用提供的数据,例如,可以使用以下内容:
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()
this gives: 这给出了:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.