【问题标题】:Grouped bar plot using replicates使用重复的分组条形图
【发布时间】:2018-12-14 01:01:04
【问题描述】:

我在其他组条形图对话中找不到答案。每个重命名(或站点名称)应加起来 100%,但条形加起来不止于此。我想知道我的数据是否设置不正确。

我也想添加误差线,但也许一旦我得到正确的复制,我就能弄清楚。

testData <- read.csv("composition.csv")
testData$id <- as.factor(testData$rename) 
testDataMelt <- reshape2::melt(testData, rename.vars = "rename")
ggplot(testDataMelt, 
       aes(x = rename, y =value, group = replicate, fill = replicate)) + 
  geom_bar(stat = "identity", position = "dodge") +
  xlab("Lake") + 
  ylab("% of Sediment Mass") +
  labs(fill = "") + 
  scale_fill_grey()

【问题讨论】:

  • 您需要在之前汇总您的数据(计算每个重命名的平均值和 SE)。
  • 请使用dput(my_data) 显示您的数据,而不是张贴图片。

标签: r ggplot2


【解决方案1】:

正如@PoGibas 所建议的,这是一个在将数据传递给ggplot 之前汇总数据的示例。

因为我没有易于使用的格式的数据,所以我会为 3 个站点制作一些假数据;与原始数据一样,每行的砾石、沙子、淤泥和粘土总计为 100%。

set.seed(2018)
df <- data.frame(rename = c("HOG", "MAR", "MO BH"),
                 gravel = sample(20:40, 9),
                 sand   = sample(40:50, 9),
                 silt   = sample(0:10, 9))
df$clay = as.integer(100 - rowSums(df[,2:4]))

这是一个带有data.table 的解决方案(这个包需要更多的广告),用于计算均值和标准误差(用于误差线)。

library(ggplot2)
library(data.table) # for aggregations 

# Convert to data.table object and 
# calculate the means and standard errors of each variable per site.
setDT(df)
testDataMelt <- melt(df, id.vars = "rename")
testDataMelt_agg <- testDataMelt[, .(mean = mean(value), 
                                     se = sd(value)/.N), 
                                 by = .(rename, variable)]
# The mean percent of sediments sum up to 100% for each site.
# We are ready to make the graph.

ggplot(testDataMelt_agg, 
       aes(x = rename, y = mean, fill = variable)) + 
  geom_bar(stat = "identity", position = "dodge") +
  # Add error bars (here +/- 1.96 SE)
  geom_errorbar(aes(ymax = mean + 1.96*se, 
                    ymin = mean - 1.96*se),
                position = "dodge") +
  xlab("Lake") + 
  ylab("% of Sediment Mass") +
  labs(fill = "") + 
  scale_fill_grey()

【讨论】:

  • 谢谢!我不熟悉data.table。很高兴知道 - 我很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多