首页 > 解决方案 > 如何对漏斗图中的条形重新排序

问题描述

我想绘制一个漏斗图,但所有的条形图都没有正确排序。

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但它不起作用

标签: rggplot2data-visualizationbar-chartgeom-bar

解决方案


您有正数和负数,但想按总长度排序,所以我们需要对绝对值求和并按以下顺序排序:

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比例,因为我没有brksand labels,但是您的x比例(翻转为垂直)是离散的,而不是连续的 - 并且要小心覆盖标签和手动设置中断,这可能会覆盖排序。我留下了中断并使用了一个匿名函数labels来粘贴“区”。

在此处输入图像描述


推荐阅读