R更改条形图顺序分组的箱形图(填充变量)

时间:2019-01-28 13:03:00

标签: r dataframe ggplot2

edit:我重写了整个帖子,包括一个可以直接复制的示例,还包含PawełChabros提供的解决方案。谢谢PawełChabros提供了一个非常简洁的答案!

在下面的图片中,我很难逆转方框图的顺序,想将其从左到右从10月更改为12月:

Click here to display plot

数据框由创建

library(dplyr)
library(ggplot2)
library(forcats)

name <- c('A','A','A', 'A','A','A', 'A','A','A', 
          'B','B','B', 'B','B','B', 'B','B','B',
          'C','C','C', 'C','C','C', 'C','C','C')
month = c("oct 2018", "oct 2018", "oct 2018","nov 2018", "nov 2018", "nov 2018","dec 2018", "dec 2018", "dec 2018",
         "oct 2018", "oct 2018", "oct 2018","nov 2018", "nov 2018", "nov 2018","dec 2018", "dec 2018", "dec 2018" ,
         "oct 2018", "oct 2018", "oct 2018","nov 2018", "nov 2018", "nov 2018","dec 2018", "dec 2018", "dec 2018" )
value <- seq(1:length(month))

df = data.frame(name, month, value)
df

数据框看起来像这样

name    month   value
A   oct 2018    1
A   oct 2018    2
A   oct 2018    3
A   nov 2018    4
A   nov 2018    5
A   nov 2018    6
A   dec 2018    7
A   dec 2018    8
A   dec 2018    9
B   oct 2018    10
B   oct 2018    11
B   oct 2018    12
B   nov 2018    13
B   nov 2018    14
B   nov 2018    15
B   dec 2018    16
B   dec 2018    17
B   dec 2018    18
C   oct 2018    19
C   oct 2018    20
C   oct 2018    21
C   nov 2018    22
C   nov 2018    23
C   nov 2018    24
C   dec 2018    25
C   dec 2018    26
C   dec 2018    27 

上图中的图是由

创建的
wantedMonths = c("oct 2018", "nov 2018", "dec 2018")
wantedNames = c("A", "B")
df2= df[df$name %in% wantedNames, ] 
ggplot(df2[df2$month %in% wantedMonths , ])  +  geom_boxplot(aes(as.factor(name), value, fill=month))#fct_rev(month)

由PawełChabros提供的创建正确绘图的命令是

ggplot(df2[df2$month %in% wantedMonths , ])  +  geom_boxplot(aes(as.factor(name), value, fill=fct_rev(month)))

3 个答案:

答案 0 :(得分:0)

如果您的问题是杆的排序,则可以通过scale_colour_manual功能手动设置它们。 只需在使用ggplot进行绘图时添加此内容即可。 scale_colour_manual(values = c(“ red”,“ green”,“ blue”))

答案 1 :(得分:0)

答案(也包含在已编辑的问题中)是使用fct_rev:

ggplot(df2[df2$month %in% wantedMonths , ])  +  geom_boxplot(aes(as.factor(name), value, fill=fct_rev(month)))

答案 2 :(得分:0)

ggplot为此使用因子的顺序。您可以在ggplot调用中将月份设置为有序因子,也可以在数据中之前将其更改。在这种情况下,只需在ggplot调用之前添加以下行:

df[['month']] = ordered(df[['month']], levels = c('oct 2018', 'nov 2018', 'dec 2018'))