2017-10-17 129 views
0

我在ggplot中创建了一个barplot,但纯粹出于美学原因,我想更改图例类别的顺序。这里是我的脚本:更改图例顺序ggplot酒吧

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 

plot 我不想用数据做任何事情,我只是想改变联想秩序,使darkblue类别“离群”是在lightblue类的顶部描述'NOutlier'。

任何人都知道一个快速的方法来做到这一点?

回答

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")) 

enter image description here

或者,您也可以重用的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 abou改变图例标签的顺序。