我正在尝试制作一个条形图,显示7个国家的费用和收入,我想按他们的费用订购。问题是ggplot是按收入排序的,我不知道如何告诉ggplot在我调整数据帧时应该使用哪些变量。我该怎么做?
我首先尝试使用reorder(),它在收入后排列条形图,然后我尝试使用arrange(),在旋转之前和之后都不起作用。我还尝试手动估算顺序,它确实按照我想要的顺序排列了它们,但不知怎的,它弄乱了条形图之间的间距。
如有任何帮助,我们将不胜感激!
#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')
)