当美学填充基于两个因素的相互作用时,我想切换堆叠的钢筋顺序。我尝试使用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")
有人知道我如何仍然可以更改堆叠顺序,以使夏天栏位于底部吗?在下面的示例中,夏季条位于顶部(细条)。我想要他们在底部。
答案 0 :(得分:2)
由于列“ 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)