r - ggplot2调色板图例不显示

标签 r ggplot2 legend palette

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

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

这是一个代码示例:

## 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(红到蓝)和垂直:

enter image description here

谢谢

最佳答案

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

enter image description here

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

enter image description here

如果您想以相反的顺序映射值,可以使用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)

enter image description here

关于r - ggplot2调色板图例不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304818/

相关文章:

r - 在线条末端绘制标签

python - 如何更改图例中字体的文本颜色?

R - 在 ggplot2 (geom_col) 中更改形状图例

R CMD 检查 : no visible binding for global variable ‘mypkgdata’

r - 如何使用ggplot2的x轴日期注释?

r - 在月轴上准确放置 geom_text 标签

r - 独立于行构面的数量来控制ggplot2构面的高度

R: "extdata"的含义?

r - 向量化更改矩阵列的 for 循环

r - r 中带有 geom_raster 的热图