2016-08-26 17 views
0

我是ggplot2中的絕對初學者。我對ggplot2感到沮喪,並開始閱讀韋翰的真棒​​書。他說,「一個規模是每個審美使用的情節所需的。」。劇情中使用的美學比例| ggplot2

所以,我做了以下內容:

嘗試1:

huron <- data.frame(year = 1875:1972, level = as.numeric(LakeHuron)) 
    ggplot(huron, aes(year)) + 
    geom_line(aes(y = level + 5, color = "y+5")) + 
    scale_color_manual(values = c("orange")) + 
    geom_line(aes(y = level - 5, color = "y-5")) + 
    scale_color_manual(values = "blue") 

在運行此,我得到一個錯誤說" insufficient value of colors provided."

我GOOGLE了這一點,並發現了以下線程SO:ggplot2 Error: Insufficient values in manual scale。在原始文章中,爲什麼他/她添加了額外的顏色是有道理的。不過,我不確定爲什麼在我的例子中會出現這種情況,因爲我有兩層,每層都有自己的美學。

嘗試2

此代碼將工作:(在我可以看到兩種不同顏色的兩個線路圖和legend-- 這是我的目標

ggplot(huron, aes(year)) + 
    geom_line(aes(y = level + 5, color = "y+5")) + 
    scale_color_manual(values = c("orange", "blue")) + #Added another color here. 
    geom_line(aes(y = level - 5, color = "y-5")) 

令人驚訝,上面的代碼顯示了一些奇怪的東西 - 我有兩個美學,只有一個比例。

問題1:這是相當令人驚訝的,因爲我們可以看到有兩個幾何,但只有一個尺度。正確?我知道韋翰不會錯。那麼,我錯過了什麼?

問題2:此外,出於好奇,如果我有多個geoms每一個審美在上述情況下,與一個規模綁各的,怎麼會ggplot知道哪個規模的關係回到其GEOM?和ggplot2一樣,ggplot2如何知道layer1是否與color = red一起縮放,layer2是否與color = blue一起?

我真誠感謝您的想法。提前致謝。


+1

你有一個審美的存在。您將第二個調用添加到aes並不會改變,只會定義(一個)顏色審美映射。在ggplot2圖中只能有一個色標。 – Roland

+0

@羅蘭感謝您的幫助。所以,如果我正確地理解了你 - 儘管我有許多美學,但最多隻能有一個色階。然而,如果我想要改變不同美學的顏色,例如在這個例子中:'ggplot(mpg,aes(displ,hwy))+ geom_point(aes(color = class))+ geom_smooth(method = 「lm」,se = FALSE,color =「red」)'這裏,我有兩種美學的不同顏色。不是嗎? – watchtower

+1

在這個例子中,你有一個審美映射('class'映射到顏色,只有這將導致圖例)。在'geom_smooth'中,你不使用'aes',只定義一個「手動」顏色。 – Roland

回答

2

要回答的意見的具體問題:

如果要強制特定的顏色,你需要使用scale_color_manual。顧名思義,這需要一些手動工作。

library(ggplot2) 

#default colors 
#http://stackoverflow.com/a/8197703/1412059 
gg_color_hue <- function(n) { 
    hues = seq(15, 375, length = n + 1) 
    hcl(h = hues, l = 65, c = 100)[1:n] 
} 

ggplot(mpg, aes(displ, hwy)) + 
    geom_point(aes(colour = class)) + 
    geom_smooth(method = "lm", se = FALSE, aes(color = "model")) + 
    scale_color_manual(values = setNames(c(gg_color_hue(length(unique(mpg$class))), "red"), 
             c(unique(mpg$class), "model"))) 

resulting plot

然而,我會使用額外的美學爲線型。

ggplot(mpg, aes(displ, hwy)) + 
    geom_point(aes(colour = class)) + 
    geom_smooth(method = "lm", se = FALSE, aes(linetype = "model"), color = "red") 

second resulting plot

+0

太棒了。我想使用override.aes來顯示圖例:'ptry <-ggplot(mpg,aes(displ,hwy))+ geom_point(aes(color = class))+ geom_smooth(method =「lm」,se = FALSE, aes(color =「lm」))+ scale_color_manual(「Direction」,values = c(「lm」=「purple」,「2seater」=「green」,「compact」=「blue」,「midsize」=「yellow 「,」minivan「=」洋紅色「,」皮卡「=」橙色「,」微型「=」青色「,」SUV「=」紅色「))'然後,我會重寫傳說:'ptry + guides(guide_legend (override.aes = list(linetype = c(rep(「blank」,2),「solid」,rep(「solid」,5))),shape = c(rep(16,2),NA,rep 16,5))))'。這不起作用。 – watchtower

+0

@羅蘭德 - 你能幫我理解我的代碼在評論部分有什麼問題嗎?如果代碼不清楚,我很抱歉。我可以添加上面的問題。請告訴我。 – watchtower

+0

如果您有新問題,請提出一個新問題。我不知道你在努力達到什麼目標,因此不知道「不起作用」是什麼意思。 – Roland

相關問題