r语言 - 我的 ggplot 条形图重新排序() 函数不起作用



我正在尝试将条形图按降序重新排序(接触率最高的路组位于顶部(。但是,reorder(( 函数似乎不起作用。

for (i in uniq_wards) 
{ print(ggplot(data = subset(roads, Ward == i),
aes(x = reorder(Roadgroup, Contact.rate),
y = Contact.rate,
fill = undecided_rate)) +
geom_col() +
coord_flip() +
labs(fill = "Undecided rate", y = "Contact Rate", x = "Road Group") +
theme(axis.text.x = element_text(angle = 90),
text = element_text(size = 8)) +
scale_fill_gradient(low = "gray", high = "blue", limits=c(0.0, 0.35)) +
ggtitle(i, subtitle = "Contact Rate and Undecided Density")) 
}

示例 ggplot

第二张图片是我希望第一个图看起来像的降序示例,它使用相同的变量轴 reorder(( 代码:

x = reorder(Roadgroup, Contact.rate),
y = Contact.rate,

工作示例

没有数据很难提供帮助。您可以尝试以下操作。我只在您的原始代码中添加了FUN = sum。如果不起作用,请提供一些示例数据。

library(tidyverse) 
for (i in uniq_wards) 
{ print(ggplot(data = subset(roads, Ward == i),
aes(x = reorder(Roadgroup, Contact.rate, FUN = sum),
y = Contact.rate,
fill = undecided_rate)) +
geom_col() +
coord_flip() +
labs(fill = "Undecided rate", y = "Contact Rate", x = "Road Group") +
theme(axis.text.x = element_text(angle = 90),
text = element_text(size = 8)) +
scale_fill_gradient(low = "gray", high = "blue", limits=c(0.0, 0.35)) +
ggtitle(i, subtitle = "Contact Rate and Undecided Density")) 
}

最新更新