2015-04-28 128 views
-1

我正在繪製使用ggplot(我的代碼如下)的年度需求,但我無法將圖例的顏色圖例。我的data.frame有「Zone」和「TotalDemand」(只有2列),我有三年的三個數據框架(「sales12」,「sales13」和「sales14」)。無法在ggplot中自定義圖例

ggplot() + 
geom_point(data=sales12, aes(x=factor(Zone), y=TotalDemand/1000), 
      color='green',size=6, shape=17) + 
geom_point(data=sales13, aes(x=factor(Zone), y=TotalDemand/1000), 
      color='red',size=6, shape=18)+ 
geom_point(data=sales14, aes(x=factor(Zone), y=TotalDemand/1000), 
      color='black',size=4, shape=19) + 
labs(y='Demand (in 1000s)',x='Zones') + 
scale_colour_manual(name = 'the colour', 
        values = c('green'='green', 'black'='black', 'red'='red'), 
        labels = c('12','13','14')) 

請幫我找出我的錯誤。

+0

可能是我的問題不清楚,所以它已經收到了投票。我已經使用了三種顏色3年,我無法將它們作爲傳說。我試圖在發佈我的問題之前查看相關帖子提供的幫助。 :) – miku

+0

你不需要像那樣放置三次'geom_point'。爲年份創建一個變量,在aes中,您可以使用它來調整點數。它非常基本的ggplot。這表明你在發佈這個問題之前還沒有讀過任何東西。如果你能提供一個可重複的例子,你將得到一個答案。 – Koundy

+1

如果你想要一個圖例,你必須將某些東西映射成'aes'的顏色。 – Roland

回答

1

對於非常小的示例數據幀df,我將它融化爲ggplot的格式。

dput(df) 
structure(list(Zone = structure(1:4, .Label = c("Alpha", "Baker", 
"Charlie", "Delta"), class = "factor"), TotalDemand = c(90L, 
180L, 57L, 159L), sales12 = c(25L, 40L, 13L, 50L), sales13 = c(30L, 
60L, 16L, 55L), sales14 = c(35L, 80L, 28L, 54L)), .Names = c("Zone", 
"TotalDemand", "sales12", "sales13", "sales14"), class = "data.frame", row.names = c(NA, 
-4L)) 

df.m <- melt(df, id.vars = "Zone", measure.vars = c("sales12", "sales13", "sales14")) 

ggplot(df.m, aes(x=factor(Zone), y=value, color = variable)) + 
    geom_point(size=6, shape=17) + 
    labs(y='Demand (in 1000s)',x='Zones') + 
    scale_colour_manual(values = c('green', 'black', 'red')) 

你可以調整你的觀點的大小和形狀和顏色,添加標題等。你的傳奇,也可以放置在底部,例如。

enter image description here

+0

非常感謝。 :) – miku