R:ggplot 使用 facet_wrap 和 coord_flip 对 x 轴重新排序
R: ggplot reorder x-axis with facet_wrap and coord_flip
我有两个数据框,我想使用 facet_wrap 绘制在一起,如下所示:
# create data frames
d = data.frame(
f = rep(c("f1", "f2"), each = 4),
x = rep(c("a", "b", "c", "d"), 2),
y = c(0, 2, 3, 3, 2, 1, 0, 6))
# plot ggplot
ggplot(d, aes(x, y)) +
geom_col() +
facet_wrap(~ f) +
coord_flip()
结果:
两个图共享它们的 x 轴,我将其翻转到一边。但是,x 轴的顺序遵循字母顺序。这不是我想要的。相反,我想使用以下从上到下的顺序手动订购 x 轴:“a”、“c”、“d”、“b”。
我尝试通过以下代码对 x 轴值进行预排序,但效果为零:
d2 = d[order(c("a", "a", "c", "c", "d", "d", "b", "b")),]
ggplot(d2, aes(x, y)) +
geom_col() +
facet_wrap(~ f) +
coord_flip()
还有很多其他问题,人们希望使用不同的顺序分别重新排序所有图的 x 轴,例如 ,但是 我想做所有这些一次对所有地块使用相同的顺序。有谁知道如何在保持简单的同时做到这一点?
您需要将 x
转换为 factor
并手动输入值。在这种情况下,由于您的轴已翻转,因此您需要将列表放入...翻转。
library(tidyverse)
d = data.frame(
f = rep(c("f1", "f2"), each = 4),
x = rep(c("a", "b", "c", "d"), 2),
y = c(0, 2, 3, 3, 2, 1, 0, 6))
d$x <- factor(d$x, levels= c('b','d','c','a'))
# plot ggplot
ggplot(d, aes(x, y)) +
geom_col() +
facet_wrap(~ f) +
coord_flip()
我有两个数据框,我想使用 facet_wrap 绘制在一起,如下所示:
# create data frames
d = data.frame(
f = rep(c("f1", "f2"), each = 4),
x = rep(c("a", "b", "c", "d"), 2),
y = c(0, 2, 3, 3, 2, 1, 0, 6))
# plot ggplot
ggplot(d, aes(x, y)) +
geom_col() +
facet_wrap(~ f) +
coord_flip()
结果:
两个图共享它们的 x 轴,我将其翻转到一边。但是,x 轴的顺序遵循字母顺序。这不是我想要的。相反,我想使用以下从上到下的顺序手动订购 x 轴:“a”、“c”、“d”、“b”。
我尝试通过以下代码对 x 轴值进行预排序,但效果为零:
d2 = d[order(c("a", "a", "c", "c", "d", "d", "b", "b")),]
ggplot(d2, aes(x, y)) +
geom_col() +
facet_wrap(~ f) +
coord_flip()
还有很多其他问题,人们希望使用不同的顺序分别重新排序所有图的 x 轴,例如
您需要将 x
转换为 factor
并手动输入值。在这种情况下,由于您的轴已翻转,因此您需要将列表放入...翻转。
library(tidyverse)
d = data.frame(
f = rep(c("f1", "f2"), each = 4),
x = rep(c("a", "b", "c", "d"), 2),
y = c(0, 2, 3, 3, 2, 1, 0, 6))
d$x <- factor(d$x, levels= c('b','d','c','a'))
# plot ggplot
ggplot(d, aes(x, y)) +
geom_col() +
facet_wrap(~ f) +
coord_flip()