r - R中的反向分组条形图
解决方案
这将按酶和伦理对虚拟数据组进行汇总并获得“值”列的平均值,然后绘制图。在 geom_col 中, position="dodge" 可以帮助创建“分组”列,而 coord_flip 将翻转 x 和 y 轴。
library(tidyverse)
#dummy data
data <- tibble(participant = 1:30,
ethnicity = sample(c("e1", "e2"), 30, replace = T),
value = sample(-10:10, 30, replace = T),
enzyme = c(rep("enzyme1", 10), rep("enzyme2", 10), rep("enzyme3", 10)))
#get mean value of 'value'
data2 <- data %>%
group_by(enzyme, ethnicity) %>%
summarize(value = mean(value))
ggplot()+
geom_col(data = data2, aes(x = enzyme,
y = value,
fill = ethnicity),
position = "dodge")+
geom_hline(aes(yintercept = 0))+
coord_flip()+
theme_linedraw()
此外,如果您的数据在 3 个单独的列中包含酶的值,您应该使用 pivot_longer 从数据转换为长格式以使绘图更容易:
data_wide <- tibble(ethnicity = c("ethnicity1", "ethnicity2"),
enzyme1 = c(-1, -2),
enzyme2 = c(0, 0),
enzyme3 = c(1, 2))
# A tibble: 2 x 4
ethnicity enzyme1 enzyme2 enzyme3
<chr> <dbl> <dbl> <dbl>
1 ethnicity1 -1 0 1
2 ethnicity2 -2 0 2
#transform to long
data_long <- data_wide %>%
pivot_longer(starts_with("enzyme"), "enzyme")
# A tibble: 6 x 3
ethnicity enzyme value
<chr> <chr> <dbl>
1 ethnicity1 enzyme1 -1
2 ethnicity1 enzyme2 0
3 ethnicity1 enzyme3 1
4 ethnicity2 enzyme1 -2
5 ethnicity2 enzyme2 0
6 ethnicity2 enzyme3 2
推荐阅读
- azure-devops - 并行发送许多查询时,TFS WorkItemTrackingHttpClient 很慢
- python - python - 在没有 gui 的情况下在 linux 中控制鼠标
- flutter - 我得到了小部件库捕获的异常
- javascript - 所有谷歌字体重量都没有在 Safari 中加载
- python - 列中的混合数据类型:int() 以 10 为底的无效文字
- python - 在 Pandas 中可以使用这种数据帧结构吗?
- c# - 如果一个键具有直接从文件读取的数据(不可打印字符),如何反序列化 json 数据
- python - 纯 Django 中的日期时间选择器
- html - java primefaces上奇怪的HTML Id属性
- r - 如何在 ifelse 命令中为 R 中的数据框编写多个“或”条件