【问题标题】:R Change bar order grouped box-plot (fill-variable)R更改条形顺序分组箱线图(填充变量)
【发布时间】:2019-01-28 13:03:00
【问题描述】:

编辑:我重写了整个帖子,包括一个可以直接复制的示例,还包含 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)))

【问题讨论】:

  • 尝试用这个函数包裹var3forcats::fct_rev()
  • 您可以使用dput(head(df,15)) 添加示例数据吗?您还可以解释一下您的代码试图实现的目标吗? ggplot(df2[df2$var3 %in% wantedVar1s , ])
  • Pawel Chabros: 成功了!我重写了整个帖子,包括你的答案。谢谢!
  • NelsonGon:我重写了整篇文章。现在应该更容易理解了。它现在还包括一个解决方案。

标签: r dataframe ggplot2


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您的问题是条形图的顺序,您可以通过scale_colour_manual 函数手动设置它们。 只需在使用 ggplot 绘图时添加这个。 scale_colour_manual(values = c("red","green","blue"))

    【讨论】:

    • 请编辑您的答案以提供更多详细信息(包括代码)。否则,最好留下评论。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-01-06
      • 2022-01-17
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多