ggplot2 调色板图例不显示

ggplot2 palette legend does not show

我刚开始使用 ggplot2 R 包,下面的问题应该很简单,但是我花了 2 小时没有成功。

我只需要在 ggplot 上显示 RdBu 调色板的 scale_fill_distiller 图例从 -1 到 1(红色到蓝色)。

这是一个代码示例:

## 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) 

RdBu 调色板的图例应该会自动弹出,但这里不会。是否有任何图层遮盖它?

有没有办法从头开始创建一个新的图例并将其添加到上面的情节中?

我需要像下图这样的东西,但是从 -1 到 1(红色到蓝色)和垂直:

谢谢

limits中指定的范围应该是c(min, max)而不是c(max, min):

这按预期工作:

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))

limits = c(1, -1) 生成没有颜色条的图:

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))

如果您想以相反的顺序映射值,可以使用 direction 参数:

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)