当美学填充基于两个因素的相互作用时,更改堆叠的钢筋顺序 [英] Change stacked bar order when aesthetic fill is based on the interaction of two factors

查看:35
本文介绍了当美学填充基于两个因素的相互作用时,更改堆叠的钢筋顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当美学填充基于两个因素的相互作用时,我想切换堆叠的钢筋顺序.我尝试使用 order = desc(),但是它不起作用.下面是一个示例:

I want to switch the stacked bar order when the aesthetic fill is based on the interaction of two factors. I tried to use order = desc() but it doesn't work. Below an example:

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")

有人知道我如何仍然可以更改堆叠顺序,以使夏天栏位于底部吗?在下面的示例中,夏季栏位于顶部(细杆).我想要他们在底部.

Does anyone know how I can still change the stacked order such that the summer bar is at the bottom? In the example below the summer bars are at the top (the thin ones). I would like them at the bottom.

推荐答案

由于降雨"列是因子列,因此按顺序绘制值.默认为字母顺序.要更改打印顺序,您需要指定因子的顺序.

Since the column "rainfall" is a factor column, the values are plot in order. The default is in alphabetical order. To change the plotting order, you need to specify the order of the factors.

在此问题中,将 levels = c('winter to spring','summer')添加到因子定义将从字母顺序更改为所需顺序.

In this problem adding levels=c('winter to spring', 'summer') to factor definition will change from alphabetical to the desired order.

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)  

这篇关于当美学填充基于两个因素的相互作用时,更改堆叠的钢筋顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆