我想制作一个Z的条形图,由一个称为Y的分组变量分组,然后进一步分组为X。我敢肯定有一种绘制此图形的理想方法,但这就是我所掌握的。>
HW1bii <- HW1b %>%
group_by(Y,X)
ggplot(data = HW1bii, mapping = aes(x = Z)) +
geom_bar(color = "Black", fill = "steelblue")
并不是我要找的东西,但我希望有人能帮助我找到更好的东西。
structure(list(X = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,
4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 7L, 7L), Y = c(1L, 2L, 3L,
1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L, 3L), Z = c(113L, 109L, 105L, 80L, 122L, 88L, 104L, 98L, 93L,
105L, 99L, 105L, 99L, 105L, 94L, 104L, 110L, 109L, 106L, 93L,
125L)), row.names = c(NA, -21L), class = c("tbl_df", "tbl", "data.frame"
))
答案 0 :(得分:2)
有很多方法可以做到这一点。这是在x轴上绘制X
,使用Y
按facet_grid
分组的图。
library(ggplot2)
ggplot(data = HW1b, aes(x = factor(X), y = Z)) +
geom_bar(stat = "identity", color = "Black", fill = "steelblue", width = 0.5) +
scale_x_discrete(name = "X") +
facet_grid(Y ~ .)
您也可以使用coord_flip
来移动轴。
ggplot(data = HW1b, aes(x = factor(X), y = Z)) +
geom_bar(stat = "identity", color = "Black", fill = "steelblue", width = 0.5) +
scale_x_discrete(name = "X") +
coord_flip() +
facet_grid(Y ~ .)
或使用facet_grid(Y ~ X, scales = "free_x)
ggplot(data = HW1b, aes(x = factor(X), y = Z)) +
geom_bar(stat = "identity", color = "Black", fill = "steelblue", width = 0.5) +
scale_x_discrete(name = "") +
facet_grid(Y ~ X, scales = "free_x")
或将Y
映射到fill
。
ggplot(data = HW1b, aes(x = factor(X), y = Z, fill = factor(Y))) +
geom_bar(stat = "identity", color = "Black", width = 0.5) +
scale_x_discrete(name = "X") +
scale_fill_viridis_d(name = "Y") +
coord_flip()
或使用position = "dodge"
创建组条形图。
ggplot(data = HW1b, aes(x = factor(X), y = Z, fill = factor(Y))) +
geom_bar(stat = "identity", position = "dodge", color = "Black", width = 0.5) +
scale_x_discrete(name = "X") +
scale_fill_viridis_d(name = "Y")
这不是条形图,但是您也可以考虑使用geom_tile
将Z
映射为fill
。
ggplot(data = HW1b, aes(x = X, y = Y, fill = Z)) +
geom_tile(color = "Black") +
scale_fill_viridis_c()
数据
HW1b <- structure(list(X = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L,
4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 7L, 7L), Y = c(1L, 2L, 3L,
1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L, 3L), Z = c(113L, 109L, 105L, 80L, 122L, 88L, 104L, 98L, 93L,
105L, 99L, 105L, 99L, 105L, 94L, 104L, 110L, 109L, 106L, 93L,
125L)), row.names = c(NA, -21L), class = c("tbl_df", "tbl", "data.frame"
))
答案 1 :(得分:0)