Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colour palette with ggplot

Tags:

plot

r

ggplot2

In order to produce replicable example I would have to submit shapefile data etc. and that would be cumbersome for you (downloading data etc.) so here is a attempt just by providing the last part and that's about the ggplot

Here is sample code:

cols <- colorRampPalette(c("darkgreen","yellow","red"), space = "rgb")
myPal <- cols(11) 

ggplot(data=df, aes(x=long, y=lat, group=group)) + 
   geom_polygon(aes(fill = measure))+    # draw polygons
   coord_equal() +
   scale_x_continuous(breaks = as.numeric(levels(factor(df$measure))))+
   scale_fill_manual(values = myPal)+
   labs(title="mesure level", x="", y="")+
   theme(axis.text=element_blank(),axis.ticks=element_blank())

Basically, I'm trying to apply my own colours to fill the regions by defining the colour range. The above doesn't work as it produces error:

Error: Continuous value supplied to discrete scale

EDIT: This works however:

ggplot(data=df, aes(x=long, y=lat, group=group)) + 
  geom_polygon(aes(fill = measure))+    # draw polygons
  coord_equal() +
  geom_path(color="grey", linestyle=2)+
  scale_fill_gradient(low = "#ffffcc", high = "#ff4444", 
                  space = "Lab", na.value = "grey50",
                  guide = "colourbar")+
  labs(title="measure level", x="", y="")+
  theme(axis.text=element_blank(),axis.ticks=element_blank())

EDIT2: The measure variable is numeric(), and here is how I insert the measure:

  df$measure <- as.numeric(round(runif(nrow(df), 0, 1), 1))

dput is huge so here is str()

str(df)
'data.frame':   344858 obs. of  8 variables:
$ long   : num  18 18 18 18 18 ...
$ lat    : num  48.7 48.7 48.7 48.7 48.7 ...
$ order  : int  1 2 3 4 5 6 7 8 9 10 ...
$ hole   : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
$ piece  : Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
$ group  : Factor w/ 80 levels "0.1","1.1","2.1",..: 1 1 1 1 1 1 1 1 1 1    ...
$ id     : chr  "0" "0" "0" "0" ...
$ measure: num  0.7 0.4 0.8 0.8 0.8 0.2 0.8 0.5 0.2 0 ...
like image 826
Maximilian Avatar asked Jul 02 '26 19:07

Maximilian


1 Answers

Yep. scale_fill_gradient is continuous. scale_fill_manual is discrete and measure definitely is numeric (and not a factor) so what you're seeing is totally expected behavior. Here's a toy example to help explain:

library(rgdal)
library(curl)
library(ggplot2)
library(ggthemes)

# get a simple shapefile

map_url <- "https://andrew.cartodb.com/api/v2/sql?filename=us_states_hexgrid&q=SELECT+*+FROM+andrew.us_states_hexgrid&format=geojson&api_key="

res <- curl_fetch_disk(map_url, "hexes.json")

hex <- readOGR("hexes.json", "OGRGeoJSON")

## OGR data source with driver: GeoJSON 
## Source: "hexes.json", layer: "OGRGeoJSON"
## with 51 features
## It has 6 fields

str(hex@data)

## 'data.frame':    51 obs. of  6 variables:
##  $ cartodb_id: int  1219 1217 1218 220 215 228 232 227 230 229 ...
##  $ created_at: Factor w/ 4 levels "2015-05-13T22:02:22Z",..: 4 2 3 1 1 1 1 1 1 1 ...
##  $ updated_at: Factor w/ 51 levels "2015-05-14T14:17:56Z",..: 20 40 47 12 44 2 3 11 19 25 ...
##  $ label     : Factor w/ 51 levels "A.K.","Ala.",..: 20 40 47 12 44 2 3 11 19 25 ...
##  $ bees      : num  60.5 47.8 33.9 13.9 46.3 48.1 42.9 34.9 44.3 38.7 ...
##  $ iso3166_2 : Factor w/ 51 levels "AK","AL","AR",..: 22 40 47 12 44 2 4 11 19 26 ...

We'll use bees since it's similar to your measure.

# make it so we can use the polygons in ggplot

hex_map <- fortify(hex, region="iso3166_2")

str(hex_map)

## 'data.frame':    357 obs. of  7 variables:
##  $ long : num  -133 -130 -130 -133 -135 ...
##  $ lat  : num  55.3 54.4 52.5 51.6 52.5 ...
##  $ order: int  1 2 3 4 5 6 7 8 9 10 ...
##  $ hole : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
##  $ piece: Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
##  $ group: Factor w/ 51 levels "AK.1","AL.1",..: 1 1 1 1 1 1 1 2 2 2 ...
##  $ id   : chr  "AK" "AK" "AK" "AK" ...

By default, bees will be considered a continuous variable and the default fill color scale will reflect that:

gg <- ggplot()
gg <- gg + geom_map(data=hex_map, map=hex_map,
                    aes(x=long, y=lat, map_id=id),
                    fill="#ffffff", color="#7f7f7f", size=0.25)
gg <- gg + geom_map(data=hex@data, map=hex_map, aes(map_id=iso3166_2, fill=bees))
gg <- gg + coord_map()
gg <- gg + theme_map()
gg <- gg + theme(legend.position="right")
gg

enter image description here

You can have ggplot use automatic cuts & a discrete colormap vs a continuous colormap with scale_fill_distiller:

gg <- ggplot()
gg <- gg + geom_map(data=hex_map, map=hex_map,
                    aes(x=long, y=lat, map_id=id),
                    fill="#ffffff", color="#7f7f7f", size=0.25)
gg <- gg + geom_map(data=hex@data, map=hex_map, aes(map_id=iso3166_2, fill=bees))
gg <- gg + scale_fill_distiller()
gg <- gg + coord_map()
gg <- gg + theme_map()
gg <- gg + theme(legend.position="right")
gg

enter image description here

You can also do a manual cut outside of the ggplot operations and pass that new column into scale_fill_manual.

If you must use a continuous color scale, please consider using the viridis colormap:

devtools::install_github("sjmgarnier/viridis")
library(viridis)

gg <- ggplot()
gg <- gg + geom_map(data=hex_map, map=hex_map,
                    aes(x=long, y=lat, map_id=id),
                    fill="#ffffff", color="#7f7f7f", size=0.25)
gg <- gg + geom_map(data=hex@data, map=hex_map, aes(map_id=iso3166_2, fill=bees))
gg <- gg + coord_map()
gg <- gg + scale_fill_viridis()
gg <- gg + theme_map()
gg <- gg + theme(legend.position="right")
gg

enter image description here

It's more accurate in general, accurately visible to the colorblind & downgrades to grayscale well (and accurately).

like image 54
hrbrmstr Avatar answered Jul 04 '26 07:07

hrbrmstr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!