【发布时间】:2020-02-22 00:53:51
【问题描述】:
在分组变量后使用facet_wrap(通常报告为here、here 等)并获得最高值时,我遇到了排序条的问题。
当我在没有因子转换的情况下运行代码时,条形图是有序的:
iris %>%
gather(key = measurements, value = values, - Species) %>%
mutate(kk = factor(measurements, levels = unique(.$measurements)),
species_l = with(., paste(Species, .$measurements, sep = "_"))) %>%
ggplot(aes(x = reorder(species_l, values),
y = values,
fill = kk)) +
geom_bar(stat = "identity") +
facet_wrap(.~kk,
scales = "free")
但现在我想在facet_wrap 和top_n 之后订购递减的条形。
到目前为止,这是我尝试过的:
library(tidyverse)
iris %>%
gather(key = measurements, value = values, - Species) %>%
within(.,
Species <- factor(Species,
levels=names(sort(table(Species),
decreasing=FALSE)))) %>%
ggplot(aes(x = Species,
y = values,
fill = measurements)) +
geom_bar(stat = "identity") +
facet_wrap(.~ measurements,
scales = "free")
还有这个:
iris %>%
gather(key = measurements, value = values, - Species) %>%
group_by(measurements, Species) %>%
top_n(5, wt = values) %>%
ggplot(aes(x = reorder(Species, Species,
function(x)-length(x)),
y = values,
fill = measurements)) +
geom_bar(stat = "identity") +
facet_wrap(.~measurements,
scales = "free")
还有这个:
iris %>%
gather(key = measurements, value = values, - Species) %>%
mutate(kk = factor(measurements, levels = unique(.$measurements)),
species_l = with(., paste(Species, .$measurements, sep = "_"))) %>%
group_by(measurements, Species) %>%
top_n(5, wt = values) %>%
ungroup() %>%
ggplot(aes(x = reorder(species_l, values),
y = values,
fill = kk)) +
geom_bar(stat = "identity") +
facet_wrap(.~kk,
scales = "free")
如您所见,Sepal.Width 条没有排序。
【问题讨论】:
-
@Tung 你可以阅读编辑。我正在尝试重新打开,因为
top_n和group_modify似乎标记为重复的答案不适合我的问题。
标签: r ggplot2 geom-bar facet-wrap top-n