【问题标题】:ggplot bar chart with error bars from data frame with multiple groupsggplot条形图,带有来自具有多个组的数据框的误差线
【发布时间】:2017-07-24 02:02:00
【问题描述】:

如果这是一个愚蠢的问题,请原谅,但如果我有这样的数据框...:

Year Location Value SE.Value 
2010   USA     10      1
2010   USA     11      1
2011   USA     12      2
2011   USA     20      4
2012   USA     13      1

我想要一个条形图,用于绘制每年的平均值,并使用 SE.Value(标准误差)的汇总来确定误差线。

这样做的正确方法是什么?

在我的方法(如下)中,我不断收到一个错误,我看到多个错误栏,因为我假设它不是计算聚合值,而是计算值之间的差异 - 每行的 SE.Value。

err_bar_limits <- aes(ymin = (df$Value - df$SE.Value), ymax = (df$Value + df$SE.Value))

ggplot(data=df, aes(x=df$Year, y=df$Value)) + geom_bar(position="dodge", stat="identity") + geom_errorbar(err_bar_limits, width=0.2, position="dodge")

对于上述错误的示例,我的意思是:

由于上述问题,我调整为尝试...:

avg_vals <- aggregate(df$Value, list(df$Year), mean)
avg_se_vals <- aggregate(df$SE.Value, list(df$Year), mean)

我相信这应该给我一个数据框,其中包含按“年份”分组的 value 或 SE.Value 的平均值,对吗?

然后我从那里尝试...:

err_bar_limits <- aes(ymin = (avg_vals$Value - avg_se_vals$SE.Value), ymax = (avg_vals$Value + avg_se_vals$SE.Value))

ggplot(data=df, aes(x=df$Year, y=df$Value)) + geom_bar(position="dodge", stat="identity") + geom_errorbar(err_bar_limits, width=0.2, position="dodge")

但我得到一个错误

Aesthetics must be either length 1 or the same as the data 

我知道这可能是一个愚蠢的错误,但我之前从未真正使用过 ggplot,所以我有点卡在这里。

我知道我原来的方法是完全错误的,我需要按年份对误差条最小值/最大值进行分组,但我不确定在尝试这种方式时如何克服错误。

希望这是有道理的......

【问题讨论】:

  • 请在您的问题中包含dput(df) 的输出,以使此代码可重现。
  • 我在该场景中添加了错误图片——我包含的 img 使用的工作数据与我在上面发布的不同,但它应该能够说明问题(多个错误栏位于每个小节)。
  • 如果您还没有,请查看 ggplot 食谱:cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)

标签: r ggplot2 bar-chart data-visualization


【解决方案1】:

当您拨打您的err_bar_limits 时,您将获得以下信息:

* ymax -> avg_vals$Value + avg_se_vals$SE.Value
* ymin -> avg_vals$Value - avg_se_vals$SE.Value

geom_bar() 无法理解这一点。因此,您应该直接将其提供给geom_bar

ggplot(data=df, aes(x=df$Year, y=df$Value)) +
geom_bar(position="dodge", stat="identity") +
geom_errorbar(aes(ymin = (avg_vals$Value - avg_se_vals$SE.Value), ymax = (avg_vals$Value + avg_se_vals$SE.Value)),
width=0.2, position="dodge")

这是我的代码:

avg_vals <- aggregate(df$Value, list(df$Year), mean)
avg_se_vals <- aggregate(df$SE.Value, list(df$Year), mean)

ndf = merge(avg_vals, avg_se_vals, by = "Group.1")
names(ndf) = c("Year", "Avg", "SE")
ndf

library(ggplot2)
ggplot(data = ndf, aes(x = ndf$Year, y = ndf$Avg)) +
  geom_bar(position = "dodge", stat = "identity") +
  geom_errorbar(aes(ymax = ndf$Avg + ndf$SE, ymin = ndf$Avg - ndf$SE),
                width = 0.2, position = "dodge")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多