【发布时间】:2019-08-30 14:59:01
【问题描述】:
我有一个包含数字(百分比)和分类变量的数据框。我想生成一个堆积条形图(使用 ggplot2),其中列(分类变量)按数值变量排序。
我试过这个:
How to control ordering of stacked bar chart using identity on ggplot2
还有这个:
https://community.rstudio.com/t/a-tidy-way-to-order-stacked-bar-chart-by-fill-subset/5134
但我对因子不熟悉,想了解更多。
# Reproduce a dummy dataset
perc <- c(11.89, 88.11, 2.56, 97.44, 5.96, 94.04, 6.74, 93.26)
names <- c('A', 'A', 'B', 'B', 'C', 'C', 'D', 'D')
df <- data.frame(class = rep(c(-1, 1), 4),
percentage = perc,
name = names)
# Plot
ggplot(df, aes(x = factor(name), y = percentage, fill = factor(class))) +
geom_bar(stat = "identity") +
scale_fill_discrete(name = "Class") +
xlab('Names')
此代码生成一个图,其条形按变量“名称”排序。我想按变量“百分比”对其进行排序。即使我手动订购数据框,结果图也是一样的。
【问题讨论】: