简体   繁体   中英

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:

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 .

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: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM