我正在尝试制作一个条形图,显示 7 个国家/地区的支出和收入,并且我想按支出对它们进行排序。问题是 ggplot 按收入排序,我不知道如何告诉 ggplot 当我旋转数据框时应该使用哪些变量。我该怎么做?
我首先尝试使用 reorder(),它在收入之后排列条形,然后我尝试在旋转之前和之后使用排列(),但没有用。我还尝试手动估算顺序,这确实按照我想要的顺序排列它们,但不知何故它弄乱了条形之间的间距。
任何帮助将不胜感激!
#Replication data:
df_country <- data.frame(country = c('Denmark', 'Finland', 'Japan', 'Norway', 'Switzerland', 'Germany', 'USA'),
revenues = c(283631, 238985, 133487, 354506, 221348, 235079, 181078),
expenses = c(261849, 243311, 144859, 314360, 212768, 227343, 218995))
#My attempt, which orders by revenue:
df_country %>%
pivot_longer(cols = c('revenues', 'expenses'),
names_to = 'vars',
values_to = 'values') %>%
ggplot(aes(x = reorder(country, values), y = values, fill = vars)) +
geom_bar(stat = 'identity', width = 0.7, position = position_dodge(width = 0.9)) +
scale_y_continuous(breaks = seq(0, 3.5e+5, 5e+4)) +
scale_fill_manual(values = c('#ff9214', '#003f5c')) +
labs(x = NULL) +
theme(
axis.text.x = element_text(hjust = -0.25,
margin = margin(t = -2, unit = 'mm')),
axis.ticks = element_blank(),
panel.background = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(colour = '#909090'),
text = element_text(family = 'serif')
)