2012-09-01 33 views
13

難以設置ggplot中的地圖的色階。我需要灰度。非常感謝一個想法,我錯了。我還想知道是否有一種更有效的方法將顏色變量放入ggplot中(即將其附加到'強化'數據中)?指定ggplot中的地圖的色階

library(ggplot2) 
states <- map_data("state") 
var <- data.frame(table(states$region)) # using rows as a dummy variable 
states$variable <- var$Freq[match(states$region,var$Var1)] 

map <- ggplot(states, aes(x=long, y=lat)) + 
    geom_polygon(aes(group=group, fill=variable), col=NA,lwd=0) 

map + scale_colour_gradient(low='white', high='grey20') 
map + scale_colour_grey() 

enter image description here

+1

如果有幫助,我在工作中使用ggplot地圖包含一個函數,假設您已經強化了數據。你可以通過'''devtools :: install_github(「mapping」,「jaredlander」)來安裝'''。這裏是GitHub頁面:https://github.com/jaredlander/mapping – Jared

回答

10

您需要使用scale_fill_*,而不是scale_color_*。對於多邊形幾何體,多邊形的填充顏色與美學相關聯,而不是美學上的。一般而言,用於改變特定比例的細節的函數是例如,例如type_of_scale,例如scale_scale_fill_gradient

+2

我也這麼認爲,但是我得到了'錯誤:連續值提供給離散比例'。 – A5C1D2H2I1M1N2O1R2T1

+2

您需要使用連續的比例尺,例如'scale_fill_gradient'。 –

3

此代碼適用於我。

library(ggplot2) 
states <- map_data("state") 
var <- data.frame(table(states$region)) 
states$variable <- var$Freq[match(states$region,var$Var1)] 
map <- ggplot(states, aes(x=long, y=lat,fill=variable,group=group)) + geom_polygon() 
map + scale_fill_gradient(low='white', high='grey20') 

處理離散變量問題的簡單方法是使用調色板功能創建一個「假」連續調色板。看下面的例子。

定義調色板,在這裏我使用的十六進制代碼爲黑色和白色,但你可以使用任何顏色

gs.pal <- colorRampPalette(c("#FFFFFF","#000000"),bias=.1,space="rgb") 

現在創建一些假數據

x <- rnorm(100) 
dat <- data.frame(cbind(x)) 
dat$fac <- as.factor(sort(rep(1:5,20))) 
dat$y <- x * as.numeric(dat$fac) 

接下來的情節將其與ggplot功能scale_*類型_manual在這種情況下,因爲它的顏色 在你會使用scale_colour_manual但你會使用scale_fill_manual

ggplot(dat,aes(x=x,y=y,colour=fac))+geom_point()+scale_colour_manual(values=gs.pal(5)) 
+0

感謝@DistribEcology,有用的提示。 – geotheory

+0

如果使用'scale_colour_brewer()'函數會怎麼樣? – linello