我想画一个漏斗图,但是所有的条形图都没有正确排序。
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,但它不起作用
发布于 2021-06-16 23:56:04
你有正数和负数,但是想要按总长度排序,所以我们需要对绝对值求和并按其排序:
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 scale,因为我没有brks和labels,但是您的x scale (翻转为垂直)是离散的,而不是连续的-并且要小心手动覆盖标签和设置中断,这可能会覆盖排序。我保留了中断,并使用了一个匿名函数让labels粘贴到“区”上。

发布于 2021-06-17 00:13:09
我使用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 titlehttps://stackoverflow.com/questions/68005942
复制相似问题