有困难的设置颜色秤用于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()
您需要使用scale_fill_*
而不是scale_color_*
。 对于多边形的几何形状的多边形的填充颜色被联接到fill
审美,不将color
美感。 一般情况下,函数用来改变一个特定规模的细节scale_
aesthetic_name _
type_of_scale,如scale_fill_gradient
。
此代码对我的作品。
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))