首页 > 解决方案 > 使用 bargraph.CI 分组条形图

问题描述

我将如何使用 sciplot 库的(bargraph.CI)制作一个分组条形图,显示两个相邻的条形图,例如具有以下数据的不同树类型的草覆盖和杂草覆盖。

以 excel 中的数据为例

标签: rbar-chart

解决方案


在能够绘制数据之前,您需要以更长的格式重塑它们。为此,您可以使用tidyr

library(tidyr)
DF <- df %>% pivot_longer(., -c(plot, tree), names_to = "Type",values_to = "value")

> DF
# A tibble: 12 x 4
    plot tree  Type  value
   <int> <fct> <chr> <dbl>
 1     1 maple grass    56
 2     1 maple weed     20
 3     2 pine  grass    34
 4     2 pine  weed     45
 5     3 maple grass    72
 6     3 maple weed     15
 7     4 maple grass    32
 8     4 maple weed     47
 9     5 pine  grass    59
10     5 pine  weed     23
11     6 pine  grass    87
12     6 pine  weed      8

现在您可以使用以下方法绘制它bargraph.CI

library(sciplot)
bargraph.CI(x.factor = tree, response = value, group = Type, data = DF, 
            xlab = "Tree", ylab = "% cover",legend = TRUE, x.leg = 1,angle = 45, cex.names = 1.25)

在此处输入图像描述


使用 ggplot2 的替代方案

您也可以使用ggplot2具有提供大型自定义面板的优势来执行相同操作。但是,您必须首先计算均值和标准差。您可以通过使用dplyr包和group_bysummarise函数来做到这一点:

library(dplyr)
DF %>% group_by(tree, Type) %>% summarise(Mean = mean (value), SE = sd(value))

# A tibble: 4 x 4
# Groups:   tree [2]
  tree  Type   Mean    SE
  <fct> <chr> <dbl> <dbl>
1 maple grass  53.3  20.1
2 maple weed   27.3  17.2
3 pine  grass  60    26.5
4 pine  weed   25.3  18.6

您可以结合dplyrggplot来获得情节:

library(dplyr)
library(ggplot2)
DF %>% group_by(tree, Type) %>% summarise(Mean = mean (value), SE = sd(value)) %>% 
  ggplot(., aes(x = tree, y = Mean, fill = Type)) +
  geom_bar(stat = "identity", position = position_dodge())+
  geom_errorbar(aes(ymin = Mean-SE, ymax = Mean+SE), position = position_dodge(0.9),  width=.2)

在此处输入图像描述

数据

plot = 1:6
tree = c("maple","pine","maple","maple","pine","pine")
grass = c(56,34,72,32,59,87)
weed = c(20,45,15,47,23,8)

df = data.frame(plot, tree, grass, weed)

推荐阅读