gpt4 book ai didi

r - 当美学填充基于两个因素的相互作用时更改堆叠条形顺序

转载 作者:行者123 更新时间:2023-12-01 03:05:56 25 4
gpt4 key购买 nike

当美学填充基于两个因素的相互作用时,我想切换堆叠条形顺序。我尝试使用 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

最佳答案

由于“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

关于r - 当美学填充基于两个因素的相互作用时更改堆叠条形顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57728103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com