【问题标题】:ggplot2 palette legend does not showggplot2 调色板图例不显示
【发布时间】:2018-05-12 09:37:52
【问题描述】:

我刚开始使用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(红色到蓝色)和垂直:

谢谢

【问题讨论】:

  • 可能是theme_map 掩盖了它。
  • 不,不是。我试过没有theme_map,那是一样的..
  • 尝试从scale_fill_distiller() 中删除breaks = 50 部分?我的猜测(没有看到shape 的数据框)是它不适用于shape$param 中的任何内容...
  • 你能做一个可重现的例子吗?我没有 EUshape 有数据框
  • 更新了可重现的示例。

标签: r ggplot2 legend palette


【解决方案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)

【讨论】:

    猜你喜欢
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多