r - R中两个数据框的条形图
问题描述
我的目标是制作一个基本的条形图,其中数据来自两个具有相同变量的数据框。情节应该类似于下面的情节,但没有两个缺点。数据框应该有图例,误差线应该在条的中间。你知道怎么做吗?下面是生成该图的代码,我认为这不是bind_rows
最佳解决方案。
代码↓</p>
bind_rows(B, C, .id = "id") %>%
filter(question %in% c("Q1", "Q2")) %>%
ggplot(aes(x = question, y = mean)) +
geom_bar(aes(fill = id), stat = "identity", position = "dodge2", width = 0.5) +
geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd, width = 0.1, colour = id)) +
coord_flip()
数据框↓</p>
structure(list(question = c("Q1", "Q10", "Q11", "Q12", "Q2",
"Q3", "Q4", "Q5", "Q6", "Q7", "Q8", "Q9"), n = c(204L, 204L,
204L, 204L, 204L, 204L, 204L, 204L, 204L, 204L, 204L, 204L),
mean = c(5.22549019607843, NA, 4.95098039215686, 4.39705882352941,
5.47058823529412, 5.51470588235294, 4.50490196078431, 4.92647058823529,
4.40686274509804, 5.56862745098039, 5.56372549019608, 5.23529411764706
), sd = c(1.1524816893289, NA, 1.31214449357814, 1.5422430010719,
1.12039650223724, 1.15104553532809, 1.37714471881058, 1.34621721218454,
1.30030385262334, 0.871099231072865, 0.830963499839951, 1.36945187401243
)), row.names = c(NA, 12L), class = c("tbl_df", "tbl", "data.frame"
))
structure(list(question = c("Q1", "Q10", "Q11", "Q12", "Q2",
"Q3", "Q4", "Q5", "Q6", "Q7", "Q8", "Q9"), n = c(13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L), mean = c(5.38461538461539,
4.38461538461539, 4.69230769230769, 4.30769230769231, 5.15384615384615,
5.38461538461539, 4.76923076923077, 5.30769230769231, 4.53846153846154,
5.61538461538461, 5.69230769230769, 4.92307692307692), sd = c(1.26085034391223,
1.44559454541846, 1.03155347127648, 1.60128153805087, 0.898717034272917,
1.12089707663561, 1.01273936708367, 0.85485041426511, 0.967417922046845,
1.26085034391223, 0.85485041426511, 1.84668795692624)), row.names = c(NA,
12L), class = c("tbl_df", "tbl", "data.frame"))
解决方案
我认为dplyr::bind_rows()
在这里工作得很好。要对齐分组条和误差条,position_dodge()
请用于两个图层。
bind_rows(B, C, .id = "id") %>%
filter(question %in% c("Q1", "Q2")) %>%
ggplot() +
aes(mean, question, fill = id, xmin = mean - sd, xmax = mean + sd) +
geom_col(position = "dodge2", width = 0.5) +
geom_errorbar(position = position_dodge2(padding = 0.5), width = 0.5) +
theme_minimal()
position_dodge2()
如果要添加其他图层,也需要。
last_plot() +
geom_point(position = position_dodge2(width = 0.5))
推荐阅读
- html - CSS防止较小的字体大小不居中
- rubygems - 在 ruby on rails 5.2.4 中使用谷歌云翻译时出错
- android - 搜索 BLE 设备时不会调用 onScanResult
- sharepoint - PowerApps 中自定义的 SharePoint 列表:根据另一个下拉列表中的选择自动更改下拉列的值
- cypress - 将元素文本存储在数组中并稍后访问它
- reactjs - 错误:必须在使用 Websoket 做出反应时使用解构状态分配
- node.js - 访问 Multer.diskStorage->filename 中的 res.locals
- python - 如何在 Python 中的字符串连接操作中添加引号?
- r - 为什么我在 R 中的 ChoiceRT_ddm 函数中的 RTu[i, 1:Nu[i]] 出现错误?
- c++ - C++14 标准是否有缺陷/未指定 wrt 从初始值设定项列表中扣除数组类型函数参数?