使用bargraph.CI将Barchart分组

时间:2019-12-17 02:36:27

标签: r bar-chart

我将如何使用密文库(bargraph.CI)创建一个分组的条形图,以两个相邻的条形显示,例如草皮和杂草覆盖不同类型的树,并带有以下数据。

data from excel given as an example

1 个答案:

答案 0 :(得分:0)

在能够绘制数据之前,您需要以更长的格式对它们进行重塑。为此,您可以使用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)

enter image description here


使用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)

enter image description here

数据

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)