如何对漏斗图中的条形重新排序
Posted
技术标签:
【中文标题】如何对漏斗图中的条形重新排序【英文标题】:how to reorder bars in a funnel chart 【发布时间】:2021-09-01 11:11:52 【问题描述】:我想画一个漏斗图,但是所有的条形图都没有正确排序。
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
,但它不起作用
【问题讨论】:
你是如何尝试reorder
的?由于您有正数和负数但想按总长度排序,我认为reorder(district, N, function(x) sum(abs(x)))
会起作用。
我在coord_flip() +
之后使用reorder(N, district)
,它说Discrete value supplied to continuous scale
。我也试过你的ggplot(aes(x = reorder(district, N, function(x) sum(abs(x))), y = N, fill = covid))
同样的错误。我说错了吗?
那个问题是你有 scale_x_continuous
但你的 x 值(区)是离散的,而不是连续的。看我的回答。
【参考方案1】:
您有正数和负数,但想按总长度排序,所以我们需要对绝对值求和并按此排序:
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
和 labels
,但是您的 x
刻度(翻转为垂直)是离散的,而不是连续的 - 并且要小心覆盖标签和手动设置中断,可以覆盖排序。我留下了中断并使用labels
的匿名函数粘贴到“District”上。
【讨论】:
【参考方案2】:我使用pivot_wider
将covid
列分成两列
funnel_dt1 <- tidyr::pivot_wider(funnel_dt, names_from = 'covid', values_from = 'N')
funnel_dt1 <- funnel_df1[order(funnel_df1$after),]
funnel_dt1$district <- paste(rep('district ',nrow(funnel_dt1)), funnel_dt1$district)
funnel_df1 %>% ggplot(aes(x = reorder(district, -after))) + # Fill column
geom_bar(aes(y = before), fill = 'green', stat = "identity", width = .6) +
geom_bar(aes(y = after), fill = 'red', stat = "identity", width = .6) +
scale_x_discrete(labels = function(x) paste("District", x)) +
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
【讨论】:
以上是关于如何对漏斗图中的条形重新排序的主要内容,如果未能解决你的问题,请参考以下文章