【问题标题】:Having trouble using ggplot2 function stat_smooth使用 ggplot2 函数 stat_smooth 时遇到问题
【发布时间】:2014-10-03 14:36:57
【问题描述】:

我有以下数据:

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

但是,如您所见,图表的坐标轴很不稳定。由于某种原因,这两条线也未对齐,我不知道为什么。对此的任何帮助将不胜感激。

感谢您的关注!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    将您的 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))
    

    这将导致以下情节:


    更新:当您想在绘图中包含 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()
    

    这给出:

    【讨论】:

    • 这里有办法使用 se=TRUE 吗?这个函数似乎是手动计算标准误差,但我已经在数据框中指定了它。 (误差线有效,但最好有阴影区域。)谢谢。
    • 否,因为对于每个组的每个 x 值,您只有一个观察值。您无法从一个值计算 SE。
    • @user3298090 我添加了包含 SE 的替代方法。这是你要找的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多