2016-04-26 178 views
1

我正在製作一個餅圖,內容爲ggplot2,但我無法獲得正確的餡餅切片的顏色。着色方案餅圖,ggplot2

df <- data.frame(group = c("Information technology", "Laboratory", "Tools", 
          "Unspecified", "Other"), 
       value = c(2500, 2000, 1500, 1000, 4000)) 

# Coloring scheme 
blue1 <- "#0a3250" # darkest blue 
blue2 <- "#13517b" 
blue3 <- "#2f659f" 
blue4 <- "#518ecb" 
blue5 <- "#aac8df" 
blue6 <- "#d6e7f2" # lightest blue 
colorscheme <- scale_fill_manual(values = c(blue1, blue2, blue3, 
              blue4, blue5, blue6)) 
# Data labels: 
df <- df[!is.na(df$value),] # Only keeps non-zero segments 
lbls <- df$value/sum(df$value) 
lbls <- percent(lbls)   # Converts to string and adds % sign 
lbls[lbls == "0.0%"] <- ""  # Removes 0.0% as a label 

# we now actually plot the data: 
ggplot(df, aes(x = "", y = value, fill = group)) + 
    colorscheme + 
    geom_bar(width = 1, stat = "identity", col = "white") + 
    xlab("") + ylab("") + 
    theme_bw() + 
    geom_text(aes(x  = 1.90, 
        y  = value/2 + c(0, cumsum(value)[-length(value)]), 
        label = lbls), size = 4) + 
    coord_polar(theta = "y") + 
    theme(
     axis.text  = element_blank(), 
     panel.grid  = element_blank(), 
     panel.border = element_blank(), 
     legend.key  = element_rect(fill=NULL, colour = "white"), 
     legend.key.size = unit(0.5, "cm"), 
     legend.title = element_blank(), 
     legend.text  = element_text(size = 9) 
) 

我想要什麼:

我想在df中的第一項有顏色blue1,第二個條目blue2,等等。通過這種方式,片去按順時針順序從最暗藍色亮藍色。 此外,圖例應以與df相同的順序顯示組。

的問題是什麼:

但是,顏色不按指定位置在df,而是按字母順序排列。現在,藍色的不同色調分散在餅圖片和傳說中。

回答

1

使用係數爲您分類變量:

df <- data.frame(group=factor(x=1:5, 
     labels=c("Information technology", "Laboratory", "Tools", "Unspecified", "Other")), 
       value = c(2500, 2000, 1500, 1000, 4000))