2017-03-17 336 views
0

繼R的烹飪書(http://www.cookbook-r.com/Graphs/Legends_(ggplot2))後,我試圖使用scale_fill_manual更改ggplot中的圖中的點和線的圖例和顏色,但似乎沒有要工作 - geom_points保持黑色,geom_smooths保持藍色。下面是可重複的代碼:R:使用scale_fill_manual更改ggplot填充顏色的問題

type <- c("0", "0", "1", "2", "2", "2", "2", "1") 
votes <- c(21, 28, 52, 66, 65, 42, 48, 39) 
time <- c(1, 2, 3, 4, 5, 6, 7, 8) 
df <- data.frame(type, votes, time) 

test.plot <- ggplot(df, aes(y = votes, x = time, fill = type)) + 
geom_point() + 
geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) + 
scale_fill_manual(values=c("blue4", "purple4", "red4"), 
       breaks=c("2","1","0"), 
       labels=c("Standard", "Nonstandard", "Oddball"), 
       name="Type") 
test.plot 

我想擁有的點和線標有「標準」顯示深藍色的「非標準」點和線出現暗紫色,而「穿着或行爲古怪」分線條呈現深紅色,但所有點都顯示爲黑色,線條全部顯示爲藍色:

https://i.stack.imgur.com/IylCg.jpg

任何人都有修復?先謝謝你!

回答

1

一般來說,我會建議繪製,因爲它使得更容易代碼(意味着你可以先在數據中的值)前重新映射變量:

df$type <- factor(df$type, levels = 0:2, 
        labels = c("Oddball", "Nonstandard", "Standard")) 

test.plot <- ggplot(df, aes(y = votes, x = time, colour = type)) + 
    geom_point() + 
    geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) + 
    scale_colour_manual(values=c("Standard" = "blue4", "Nonstandard" = "purple4", 
    "Oddball" = "red4"), name="Type") 

然而,否則,你只需要改變審美colour而不是fill

test.plot <- ggplot(df, aes(y = votes, x = time, colour = type)) + 
    geom_point() + 
    geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) + 
    scale_colour_manual(values=c("blue4", "purple4", "red4"), 
        breaks=c("2","1","0"), 
        labels=c("Standard", "Nonstandard", "Oddball"), 
        name="Type") 

Plot

注線和點使用colour而不是fill,並且您只需要scale_x_manual的命名向量參數。

如果您的級別不是句法name s,則需要用雙引號括住它們(例如"Non-standard")。請參閱manual

+0

謝謝,@尼克肯尼迪。這對我來說不太合適......如果我用你的線代替我使用的scale_fill_manual線,點的顏色仍然是黑色的,而線的顏色是藍色的,現在我已經失去了所有變量/傳說也是如此。也許我把你的代碼放在了錯誤的地方? – RSS

+0

@RSS對不起,我的回答太快了一點。我在上面做了一些修改。 –

+0

明白了。謝謝,尼克! – RSS