用误差条在R中生成条形图

时间:2019-04-19 14:14:24

标签: r bar-chart

我的数据集如下:

> 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

其中acegik列为均值,b列为dfhjl各自的标准偏差。

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

1)列ac

2)列eg

3)列ik

aei可以有一种颜色,列cgh可以有不同的颜色。我也希望有错误栏。

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

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

1 个答案:

答案 0 :(得分:0)

修改

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

您可以稍微更改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

enter image description here

相关问题