我在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
我不想对数据做任何事情,我只想更改Legend命令,以便深蓝色类别&#39; Outlier&#39;描绘在浅蓝色类别的顶部&#39; NOutlier&#39;
有人知道我这么做的快捷方式吗?
答案 0 :(得分:1)
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")
另请参阅此link,了解如何更改图例标签的顺序。