2015-06-23 30 views
1

我有這種如何爲兩個不同的圖形使用相同的色階?

lat  long  val 
41.69 -71.566389 0.25756813 
41.69 -71.566389 0.325883146 
42.86 -71.959722 0.897783941 
42.86 -71.959722 0.621170816 
42.37 -71.234167 0.224426988 
41.84 -71.143333 0.048329645 

val的範圍是在我的完整數據集0-1的數據集。 我想創建兩個數字,其中一個繪製所有的值從0-1和另一個繪製0.5-1。 但都必須在相同的色標

我知道我可以將它們子集並創建兩個數字。但我不知道如何讓它們具有相同的色彩比例。

目前,我有這樣的代碼:

library(ggplot2) 
library(maps) 
usamap <- map_data("state") 
myPalette <- colorRampPalette(rev(brewer.pal(10, "Spectral"))) 
ggplot(data=df,aes(x=long,y=lat,color=val)) + 
    geom_polygon(data=usamap, aes(x=long, y=lat,group=group),colour="black", fill="white")+ 
    geom_point(size = 0.01)+ 
    scale_colour_gradientn(name = "Range",colours = myPalette(10))+ 
    xlab('Longitude')+ 
    ylab('Latitude')+ 
    theme_bw() 

回答

4

您可以將limits選項簡單地添加到scale_colour_gradientn。例如:

#Simulate some example data 
set.seed(1123) 
df = data.frame(lon = rnorm(100), lat = rnorm(100), val = runif(100)) 

# Define colour palette 
library(RColorBrewer) 
myPalette <- colorRampPalette(rev(brewer.pal(10, "Spectral"))) 

# Make plots 
library(ggplot2) 

## All points 
ggplot(df, aes(x = lon, y = lat, colour = val)) + geom_point() + 
    scale_colour_gradientn(name = "Range",colours = myPalette(10), limits = c(0, 1)) + 
    theme_bw() + xlim(-3, 3) + ylim(-3, 3) 

## Subset 
ggplot(subset(df, val >= 0.5), aes(x = lon, y = lat, colour = val)) + geom_point() + 
    scale_colour_gradientn(name = "Range",colours = myPalette(10), limits = c(0, 1)) + 
    theme_bw() + xlim(-3, 3) + ylim(-3, 3) 

結果:

Example colour scale

相關問題