使用数据集:
library(tidyverse)
df1 <- structure(list(dept = c("A", "B", "C"),
n = c(70908L, 50004L, 294614L)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -3L), .Names = c("dept", "n"))
df2 <- structure(list(dept = c("A", "B", "D", "E"),
n = c(544L, 684L, 375L, 1191L)), class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA, -4L), .Names = c("dept", "n"))
> df1
# A tibble: 3 x 2
dept n
<chr> <int>
1 A 70908
2 B 50004
3 C 294614
> df2
# A tibble: 4 x 2
dept n
<chr> <int>
1 A 544
2 B 684
3 D 375
4 E 1191
我想在具有相同填充/图例的方面创建一个有序的条形图。这是我到目前为止所能得到的:
df <- rbind(df1 %>% mutate(source = 1),
df2 %>% mutate(source = 2))
df %>% ggplot(aes(reorder(dept, n), n, fill = dept)) +
geom_bar(stat = "identity") +
coord_flip() +
facet_wrap(~source, scales = "free")
如何使reorder
功能在每个方面都有效?
答案 0 :(得分:1)
要在两个方面中订购值,请使用它创建新列var3
和reorder
。在此之后,只需将scale_x_discrete
中的标签从var3
更改回dept
。
library(tidyverse)
df <- rbind(df1 %>% mutate(source = 1),
df2 %>% mutate(source = 2)) %>%
mutate(var3 = paste(source, dept))
ggplot(df, aes(reorder(var3, n), n, fill = dept)) +
geom_bar(stat = "identity") +
coord_flip() +
xlab("dept") +
facet_wrap(~ source, scales = "free") +
scale_x_discrete(breaks = df$var3, labels = df$dept)