2017-10-17 176 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改變圖例標籤的順序。