Change colour scheme for ggplot geom_polygon in R

柔情痞子 提交于 2019-12-10 02:39:45

问题


I'm creating a map using the maps library and ggplot's geom_polygon. I'd simply like to change the default blue, red, purple colour scheme to something else. I'm extremely new to ggplot so please forgive if I'm just not using the right data types. Here's what the data I'm using looks like:

> head(m)
region      long      lat group order subregion Group.1 debt.to.income.ratio.mean    ratio total
17 alabama -87.46201 30.38968     1     1      <NA> alabama                   12.4059   20.51282    39
18 alabama -87.48493 30.37249     1     2      <NA> alabama                   12.4059 20.51282    39
19 alabama -87.52503 30.37249     1     3      <NA> alabama                   12.4059 20.51282    39
20 alabama -87.53076 30.33239     1     4      <NA> alabama                   12.4059 20.51282    39
21 alabama -87.57087 30.32665     1     5      <NA> alabama                   12.4059 20.51282    39
22 alabama -87.58806 30.32665     1     6      <NA> alabama                   12.4059 20.51282    39

> head(v)
          Group.1 debt.to.income.ratio.mean    ratio     region total
alabama       alabama                  12.40590 20.51282    alabama    39
alaska         alaska                  11.05333 33.33333     alaska     6
arizona       arizona                  11.62867 25.55556    arizona    90
arkansas     arkansas                  11.90300  5.00000   arkansas    20
california california                  11.00183 32.59587 california   678
colorado     colorado                  11.55424 30.43478   colorado    92

Here's the code:

library(ggplot2)
library(maps)

states <- map_data("state")
m <- merge(states, v, by="region")
m <- m[order(m$order),]

p<-qplot(long, lat, data=m, group=group, fill=ratio, geom="polygon")

I've tried the below and more:

cols <- c("8" = "red","4" = "blue","6" = "darkgreen", "10" = "orange") 
p + scale_colour_manual(values = cols)
p + scale_colour_brewer(palette="Set1")
p + scale_color_manual(values=c("#CC6666", "#9999CC"))

回答1:


The problem is that you are using a color scale but are using the fill aesthetic in the plot. You can use scale_fill_gradient() for two colors and scale_fill_gradient2() for three colors:

p + scale_fill_gradient(low = "pink", high = "green") #UGLY COLORS!!!

I was getting issues with scale_fill_brewer() complaining about a continuous variable supplied when a discrete variable was expected. One easy fix is to create discrete bins with cut() and then use that as the fill aesthetic:

m$breaks <- cut(m$ratio, 5) #Change to number of bins you want

p <- qplot(long, lat, data = m, group = group, fill = breaks, geom = "polygon")
p + scale_fill_brewer(palette = "Blues")


来源:https://stackoverflow.com/questions/5996513/change-colour-scheme-for-ggplot-geom-polygon-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!