r - How to create grouped bar plot instead of facet_wrap in R?
问题描述
I have a dataset that has three categorical variables. I know how to use ggplot geom_bar to create a bar plot and facet_wrap. But I want the bars to be grouped by the third categorical variable rather than wrapped. See the plot below. I want the "fall" and "winter" facets to be on top of each other. For example, I want the "fall" results in Grade 10 to be below the "winter" results within one grid. Perhaps I need to structure my data differently.
tmp = data.frame(Grade = rep(1:10, each = 6),
Placement = as.factor(rep(1:5, times = 6)),
Window = rep(c("fall", "winter"), times = 15),
Percent = rnorm(n = 30, mean = 20))
ggplot(data = tmp,
aes(x = Grade, y = Percent, fill = Placement)) +
geom_bar(stat = "identity") +
facet_wrap(vars(Window)) +
coord_flip() +
scale_x_continuous(name = "Grade",
breaks = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) +
scale_y_continuous(name = "Percent",
limits = c(0, 100))
I'd like it to look more like this:
解决方案
This is different than what you had, but much closer to the picture you showed:
ggplot(data = tmp,
aes(x = Window, y = Percent, fill = Placement)) +
geom_bar(stat= "identity",position = "fill") +
facet_wrap(~Grade, scales = "free_y", switch = "y", nrow = 10) +
coord_flip() +
scale_y_continuous(labels = scales::percent, expand = c(0,0))
推荐阅读
- python - Numpy数字不是整数?
- authentication - 注销到自定义登录页面时重定向主标题中的“我的帐户”图标
- firebase - SwiftUI:MacOS 上的 Firebase 登录
- java - 在java中将对象列表转换为地图
- visual-studio - 带有 Visual Studio 2022 的分析服务
- graph - 需要我的图形或条形图的表面图应该根据高度着色
- arrays - 函数 remove(atOffsets:) 仅在运行时抱怨错误类型
- python - Django:具有增量编号的自定义存储系统
- mongodb - 如何为以下查询编写 mongo 模板查询条件
- spring-websocket - 如何在 Spring Boot 测试中连接到安全的 Web 套接字端点