更改图例顺序绘图条 [英] Change legend order ggplot bar

查看:55
本文介绍了更改图例顺序绘图条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在gglot中做了一个条形图,但是纯粹出于美学原因,我想更改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"的顶部。

有人知道我做这件事的快捷方法吗?

推荐答案

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

这篇关于更改图例顺序绘图条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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