首页 > 解决方案 > 在 R 中生成带有误差线的条形图

问题描述

我的数据集如下所示:

> print(dataplot)
          a         b         c          d         e          f         g          h         i
[1,] 0.9685 0.0150831 0.9253333 0.03018388 0.9856667 0.01330664 0.9268333 0.05894885 0.9686667
              j         k          l
[1,] 0.01478738 0.9313333 0.07123389

其中a, c, e, g, i,k列是平均值bd, , f, h, j,列是l它们各自的标准差。

我想绘制一个barplot()包含三个组的分组,即:

1) 列ac

2) 列eg

3) 列ik

a, e,i可以有一种颜色,列c, g,可以有h不同的颜色。我也想有误差线。

我一直在尝试使用以前的脚本,但我找不到如何使条形图显示为分组并具有各自的标准偏差。

我正在学习R,所以希望我能得到一些帮助。任何输入表示赞赏!

标签: rbar-chart

解决方案


编辑

根据评论中的要求更改了标签。

您可以稍微更改 data.frame 的结构,以获取可用于以下形状的数据ggplot()

library(ggplot2)
dat <- data.frame(a=0.9685, b=0.0150831, c=0.9253333, d=0.03018388, e=0.9856667, f=0.01330664, g=0.9268333, h=0.05894885, i=0.9686667,j=0.01478738, k=0.9313333, l=0.07123389)
data <- data.frame(mean=unlist(dat[, 1:ncol(dat) %% 2 == 1]), sd=unlist(dat[, 1:ncol(dat) %% 2 == 0]))
data$x <- rownames(data)
data$category <- as.factor(sort(rep(1:3, 2)))
data$Method <- as.factor(rep(c('k-NN', 'Decision trees'), 3))
gg <- ggplot(aes(x=category, y=mean, fill=Method, group=Method), data=data)
gg <- gg + geom_bar(stat='identity', position = position_dodge(), width=.5)
gg <- gg + geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(width=.5), width=.2)
gg

在此处输入图像描述


推荐阅读