2016-05-06 84 views
0

我想給顏色的餅圖。我用scale_fill_manual(values = c("orange", "red","blue", "yellow", "green"))。我想爲蘋果提供紅色,爲橙色提供橙色,爲葡萄提供藍色等。但我的餅圖看起來不同。如何設置餅圖的特定顏色?

d1 <- data.frame(
    labels = c("orange","apple","grape","pineapple","muskmelon"), 
    value = c(1632,29,1491,1991,29) 
) 
d1$pos <- cumsum(d1$value) - 0.5*d1$value 

p1 <-ggplot(d1, aes(x="", y = value, fill = labels)) 
p1 <- p1 + geom_bar(stat="identity", width=1) 
p1 <- p1 + ggtitle("fruits") 
p1 <- p1 + panel_border() 
p1 <- p1 + coord_polar(theta = "y") 
p1 <- p1 + xlab("") 
p1 <- p1 + ylab("") 
p1 <- p1 + geom_text(aes(x="", y=pos,label=labels), size=10) 
p1 <- p1 + scale_fill_manual(values = c("orange", "red","blue", "yellow", "green")) 
p1 <- p1 + theme(legend.position="none", 
    legend.title=element_blank(), 
    axis.line=element_blank(),axis.text.x=element_blank(), 
    axis.ticks=element_blank(), 
    plot.title = element_text(lineheight=3, face="bold", color="black", size=25)) 

回答

1

help(scale_fill_manual),你可以通過一個名爲向量的values參數:

p1 + scale_fill_manual(values = c("orange" = "orange", 
            "apple" = "red", 
            "grape" = "blue", 
            "pineapple" = "yellow", 
            "muskmelon" = "green")) 
+0

非常感謝! – aayan

1

這可能有點爲時已晚。我明白,這裏的問題包是ggplot2,但只是分享我將如何使用內置餅圖功能來做到這一點。首先,我分配的顏色名稱對應每個標籤的數據幀:

d1$colours <- c("orange", "red", "blue", "yellow", "green") 

,使得我d1看起來像這樣:

labels value pos colours 
    orange 1632 816.0 orange 
    apple 29 1646.5  red 
    grape 1491 2406.5 blue 
pineapple 1991 4147.5 yellow 
muskmelon 29 5157.5 green 

然後,使用pie函數圖:

pie(x = d1$value, labels = d1$labels, col = d1$colours) 

enter image description here

相關問題