当基于两个因素的相互作用的审美填充时,如何更改堆叠条形图顺序

4

当美学填充基于两个因素的交互时,我希望您能切换堆叠条形图的顺序。我尝试使用order = desc(),但它不起作用。以下是一个示例:

library(data.table)
library(ggplot2)

country     <- rep(c('SE', 'FR', 'BE'), each = 2)
rain_fall   <- rep(c('winter to spring', 'summer'), 3)
amount_rain <- c(100, 10, 95, 5, 70, 2)
order       <- c(1, 1, 2, 2, 3, 3)

DT <- data.table(country, rain_fall, amount_rain, order)
DT[, ':='(country = factor(country), rain_fall = factor(rain_fall))]


plot_stacked <- ggplot(DT, aes(x     = reorder(country, - order), 
                               y     = amount_rain, 
                               fill  = interaction(country, rain_fall)) +
                   #I tried adding here  order = desc(interaction(country, rain_fall)))) + 
                 geom_bar(stat = "identity")

有人知道我如何改变堆叠顺序,使夏季条在底部吗?在下面的示例中,夏季条位于顶部(细条)。我想让它们在底部。

enter image description here


我认为这会很困难,因为堆叠是基于y轴的。除非你通过某些转换改变y轴或者unstack条形图,否则在我的天真看法中,我无法看到如何实现你想要做的事情。也许将位置设置为dodge(取消堆叠)? - NelsonGon
1个回答

2
由于“rainfall”列是一个因子列,因此值按顺序绘制。默认情况下是按字母顺序排列的。要更改绘图顺序,您需要指定因子的顺序。
在这个问题中,将levels=c('winter to spring', 'summer')添加到因子定义中将从字母顺序更改为所需顺序。
最初的回答:由于“rainfall”列是一个因子列,因此值按顺序绘制。默认情况下是按字母顺序排列的。要更改绘图顺序,您需要指定因子的顺序。在这个问题中,将levels=c('winter to spring', 'summer')添加到因子定义中将从字母顺序更改为所需顺序。
library(data.table)
library(ggplot2)

country     <- rep(c('SE', 'FR', 'BE'), each = 2)
rain_fall   <- rep(c('winter to spring', 'summer'), 3)
amount_rain <- c(100, 10, 95, 5, 70, 2)
order       <- c(1, 1, 2, 2, 3, 3)

DT <- data.table(country, rain_fall, amount_rain, order)
DT[, ':='(country = factor(country), rain_fall = factor(rain_fall, levels=c('winter to spring', 'summer')))]


plot_stacked <- ggplot(DT, aes(x = reorder(country, - order), 
                               y   = amount_rain, fill = interaction(country, rain_fall)) )+
                         geom_bar(stat = "identity")
print(plot_stacked)  

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接