1

我在 ggplot 中制作了一个条形图,但纯粹出于审美原因,我想更改 Legend 类别的顺序。这是我的脚本:

library(ggplot2)
df <- data.frame(Month = c(4, 5, 6, 7, 8, 9, 10, 11),
                 variable = rep(c("Outlier", "NOutlier"), 4),
                 value = c(8, 9, 10, 5, 12, 13, 9, 10))

hist_overall <- ggplot(df, aes(x = Month, y = value, fill = variable)) +
  geom_bar(stat = "identity") +
  scale_fill_manual("Legenda", values = c("Outlier" = "#1260AB", "NOutlier" = "#009BFF"))
hist_overall

阴谋 我不想对数据做任何事情,我只想更改图例顺序,以便在浅蓝色类别“NOutlier”之上描绘深蓝色类别“Outlier”。

有人知道我这样做的快速方法吗?

4

1 回答 1

2

以下更改df应该做你想做的事。我们将其定义variable为一个因子,并levels通过以所需方式对它们进行排序来手动定义该因子。

df <- data.frame(Month = c(4, 5, 6, 7, 8, 9, 10, 11),
             variable = factor(rep(c("Outlier", "NOutlier"), 4), 
             levels=(rev(levels(factor(c("Outlier", "NOutlier")))))),
             value = c(8, 9, 10, 5, 12, 13, 9, 10))

hist_overall <- ggplot(df, aes(x = Month, y = value, fill = variable)) +
geom_bar(stat = "identity") +
scale_fill_manual("Legenda", values = c("Outlier" = "#1260AB", "NOutlier" = "#009BFF"))

在此处输入图像描述

或者,您可以重用您的定义df

df <- data.frame(Month = c(4, 5, 6, 7, 8, 9, 10, 11),
         variable = rep(c("Outlier", "NOutlier"), 4),
         value = c(8, 9, 10, 5, 12, 13, 9, 10))

并以下列方式定义级别及其顺序

levels(df$variable) <- c("Outlier", "NOutlier")

另请查看有关更改图例标签顺序的链接。

于 2017-10-17T14:56:36.850 回答