r - 如何对漏斗图中的条形重新排序
问题描述
我想绘制一个漏斗图,但所有的条形图都没有正确排序。
funnel_dt <- read.csv2("https://raw.githubusercontent.com/Deborah-Jia/Complete_Analysis_da2/main/funnel_dt.csv")
funnel_dt %>% ggplot(aes(x = district, y = N, fill = covid)) + # Fill column
geom_bar(stat = "identity", width = .6) + # draw the bars
scale_y_continuous(breaks = brks, labels = lbls) + # Labels
scale_x_continuous(breaks= seq(1,23,1) ,labels=paste0("district ", as.character(seq(1, 23, 1)))) +
coord_flip() + # Flip axes
labs(title="") +
theme_tufte() + # Tufte theme from ggfortify
theme(plot.title = element_text(hjust = .5),
axis.ticks = element_blank()) + # Centre plot title
scale_fill_brewer(palette = "Dark2") # Color palette
如何将最长的条(11、13 区等)放在底部?我试过reorder
但它不起作用
解决方案
您有正数和负数,但想按总长度排序,所以我们需要对绝对值求和并按以下顺序排序:
funnel_dt <- read.csv2("https://raw.githubusercontent.com/Deborah-Jia/Complete_Analysis_da2/main/funnel_dt.csv")
funnel_dt %>%
mutate(district = reorder(district, N, function(x) -sum(abs(x)))) %>%
ggplot(aes(x = district, y = N, fill = covid)) + # Fill column
geom_bar(stat = "identity", width = .6) + # draw the bars
#scale_y_continuous(breaks = brks, labels = lbls) + # Labels
scale_x_discrete(labels = function(d) paste("District", d)) +
coord_flip() + # Flip axes
labs(title="") +
#theme_tufte() + # Tufte theme from ggfortify
theme(plot.title = element_text(hjust = .5),
axis.ticks = element_blank()) + # Centre plot title
scale_fill_brewer(palette = "Dark2") # Color palette
我注释掉了y
比例,因为我没有brks
and labels
,但是您的x
比例(翻转为垂直)是离散的,而不是连续的 - 并且要小心覆盖标签和手动设置中断,这可能会覆盖排序。我留下了中断并使用了一个匿名函数labels
来粘贴“区”。
推荐阅读
- javascript - Node / Javascript:如何将键值对数组写入csv文件,键作为标题?
- google-cloud-platform - 为什么在创建 Cloud Composer 环境时会自动创建 2 个 Pub/Sub 主题和订阅
- python - 张量流编程中的 sess.run() 和 ".eval()"
- odata - SAPUI5 表 - 从 ODATA 加载值时根据某些状态禁用整行
- r - 如何在R中组合for循环的结果并一次打印?
- spring-boot - 在客户端应用程序中使用中央 Spring Cloud 配置服务器从 GitHub 存储库读取配置
- java - 索引 0 超出长度 0 数组 3D 的范围
- apache-spark - SPARK 持久化示例
- python - 如何使用 Python 在 Huffman 树中查找父节点的值
- python - 读取一系列标题和输入值(其中 1 <= value <= 30)的程序,如下所示,提示存储在两个列表中