2015-06-23 26 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

相关问题