aaaaa
aaaaa

Reputation: 183

ggplot2 palette legend does not show

I just started using ggplot2 R package and the following question should be very trivial, however I spent 2h on it without success.

I just need to show the scale_fill_distiller legend of the RdBu palette from -1 to 1 (red to blue) on my ggplot.

Here's a code example:

## Load ggplot2 package
require(ggplot2)

## Create data.frame for 4 countries
shape = map_data("world") %>%
                 filter(region == "Germany" | region == 'Italy' | region == 'France' | region == 'UK')

## Order data.frame by country name
shape = shape[with(shape, order(region)), ]
rownames(shape) = NULL # remove rownames

##### Assign 4 different values (between -1 and 1) to each country by creating a new column 'id'
## These will be the values to be plotted with ggplot2 palette
shape[c(1:605),'id'] = 0.2
shape[c(606:1173),'id'] = -0.4
shape[c(1174:1774),'id'] = -0.9
shape[c(1775:2764),'id'] = 0.7

##### Make plot
ggplot() +
      ## plot countries borders
      geom_polygon(data = shape, aes(x = long, y = lat, group = group, fill = id), colour = 'black') +
      ## adjust coordinates
      coord_map() + 
      ## remove any background
      ggthemes::theme_map() + 
      ## add colour palette
      scale_fill_distiller(palette = 'RdBu', limits = c(1, -1), breaks = 50) 

The legend of the RdBu palette should pop out automatically but here it doesn't. Is there any layer that is masking it?

OR

Is there any way to create a new legend from scratch and add it to the above plot?

I need something like the picture below, but from -1 to 1 (Red to Blue) and vertical:

enter image description here

Thanks

Upvotes: 2

Views: 354

Answers (1)

missuse
missuse

Reputation: 19716

The range specified in limits should be c(min, max) and not c(max, min):

this works as expected:

library(ggmap)
library(ggplot2)
library(ggthemes)

ggplot() +
  geom_polygon(data = shape,
               aes(x = long, y = lat, group = group, fill = id), colour = 'black') +
  coord_map() +
  ggthemes::theme_map() +
  scale_fill_distiller(palette = 'RdBu', limits = c(-1,1))

enter image description here

while limits = c(1, -1) produces a plot without a colorbar:

ggplot() +
  geom_polygon(data = shape,
               aes(x = long, y = lat, group = group, fill = id), colour = 'black') +
  coord_map() +
  ggthemes::theme_map() +
  scale_fill_distiller(palette = 'RdBu', limits = c(1, -1))

enter image description here

If you would like to map the values in reverse order, you can use the direction argument:

ggplot() +
  geom_polygon(data = shape,
               aes(x = long, y = lat, group = group, fill = id), colour = 'black') +
  coord_map() +
  ggthemes::theme_map() +
  scale_fill_distiller(palette = "RdBu",
                       limits = c(-1, 1),
                       breaks = c(-1, 0, 1),
                       direction = 1)

enter image description here

Upvotes: 4

Related Questions