R ggplot 条的特定顺序
R ggplot specific order of bars
所以,我正在使用 ggplot 在 R 中做几个降序排列的条形图。这些图中的每一个都包含一个名为 "others" 的柱状图,它应该始终是最后一个柱状图。如何最佳地实现这一点?更一般地说:是否可以轻松地选择条形图的一个条并将其移动到最后一个位置而无需手动更改所有级别。
非常感谢,
克里斯
技巧就是使用factor,如下
library(ggplot2) # for plots
# dummy data
dat <- data.frame(
letters = c("A","B","Other","X","Y","Z"),
probs = sample(runif(6)*10,6)
)
# not what we want
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity")
# magic happens here
# factor, and push Other to end of levels using c(others, other)
dat$letters <- factor(
dat$letters,
levels = c(
levels(dat$letters)[!levels(dat$letters) == "Other"],
"Other")
)
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity")
如果您使用 + coord_flip()
,请使用 levels = rev(c(...))
进行直观排序
dat$letters <- factor(
dat$letters,
levels = rev(c(
levels(dat$letters)[!levels(dat$letters) == "Other"],
"Other"))
)
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity") + coord_flip()
所以,我正在使用 ggplot 在 R 中做几个降序排列的条形图。这些图中的每一个都包含一个名为 "others" 的柱状图,它应该始终是最后一个柱状图。如何最佳地实现这一点?更一般地说:是否可以轻松地选择条形图的一个条并将其移动到最后一个位置而无需手动更改所有级别。
非常感谢, 克里斯
技巧就是使用factor,如下
library(ggplot2) # for plots
# dummy data
dat <- data.frame(
letters = c("A","B","Other","X","Y","Z"),
probs = sample(runif(6)*10,6)
)
# not what we want
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity")
# magic happens here
# factor, and push Other to end of levels using c(others, other)
dat$letters <- factor(
dat$letters,
levels = c(
levels(dat$letters)[!levels(dat$letters) == "Other"],
"Other")
)
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity")
如果您使用 + coord_flip()
,请使用 levels = rev(c(...))
进行直观排序
dat$letters <- factor(
dat$letters,
levels = rev(c(
levels(dat$letters)[!levels(dat$letters) == "Other"],
"Other"))
)
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity") + coord_flip()