r - 使用 bargraph.CI 分组条形图
问题描述
我将如何使用 sciplot 库的(bargraph.CI)制作一个分组条形图,显示两个相邻的条形图,例如具有以下数据的不同树类型的草覆盖和杂草覆盖。
解决方案
在能够绘制数据之前,您需要以更长的格式重塑它们。为此,您可以使用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_by
和summarise
函数来做到这一点:
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
您可以结合dplyr
和ggplot
来获得情节:
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)
推荐阅读
- postgresql - 如何在没有 sqlalchemy ORM 关系的情况下加入查询
- reactjs - 即使函数已绑定,在 React 中也会出现未定义的错误
- azure - Azure - 调整大小后无法启动虚拟机
- python - 有没有办法在kivy中关闭屏幕旋转
- html - “和”css中的一些选择器
- python - 应用程序错误 Azure:ModuleNotFoundError:没有名为“flask_socketio”的模块
- c++ - 从可变模板参数创建一个 std::tuple
- sql - SQL:查询只有所有匹配值的表
- angularjs - 使用 Laravel Socialite 作为 API(社交认证)
- css - OnClick 隐藏导航栏