r - 如何使用 scale_color_brewer 修复 'continuous value supplied to discrete scale'

标签 r ggplot2 colors colorbrewer

我正在尝试制作全局数据异常(降水、温度等)的 map ,并且需要使用发散的调色板。我的代码与 scale_color_viridis 运行良好但它不容易与 scale_color_brewer 转换.我想用RdBu发散的调色板。

我试过提供值 vars函数内scale_color_brewer并使用 scale_fill brewer 但我想继续使用 geom_points 进行绘图我到目前为止。

  titletext <- paste(VAR, "Response")
  expand.grid(lon, lat) %>%
    rename(lon = Var1, lat = Var2) %>%
    mutate(lon = ifelse(lon > 180, -(360 - lon), lon),
           vars = as.vector(global.array)) %>% 
    ggplot() + 
    geom_point(aes(x = lon, y = lat, color = vars),
               size = 2.0) + 
    borders("world", colour="black", fill=NA) + 
    scale_color_brewer(type="div", palette="RdBu")+
    #scale_color_viridis(na.value="white",name = VAR) +  
    theme(legend.direction="vertical", legend.position="right", 
          legend.key.width=unit(0.4,"cm"), legend.key.heigh=unit(2,"cm")) + 
    coord_quickmap() + ggtitle(titletext) 

错误信息是

Error: Continuous value supplied to discrete scale





Warning messages: 1: In RColorBrewer::brewer.pal(n, pal) : n too large, allowed maximum for palette RdBu is 11 Returning the palette you asked for with that many colors

最佳答案

您可以对连续值进行分箱/粗粒度化,为它们提供一个离散有序的值,以映射到您选择的 Brewer 调色板中包含的离散 8 到 12 种颜色。
但我认为您正在寻找的解决方案是使用 scale_color_distiller()“提炼”它们。或 scale_fill_distiller() ggplot2 中已经包含的函数,有效地将它们转换为连续的色标。在一些规范位置提供了文档和示例:

  • https://ggplot2.tidyverse.org/reference/scale_brewer.html
  • https://ggplot2-book.org/scale-colour.html#colour-continuous
  • 关于r - 如何使用 scale_color_brewer 修复 'continuous value supplied to discrete scale',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57119146/

    相关文章:

    r - 如何在 R 中的 for 循环中保存绘图

    r - 为什么 nls 函数在 ggplot2 中不起作用

    r - 如何在箱线图R中显示单独的误差线?

    r - 在 R (ggplot) 中注释公式(使用 bqoute 或替代)给出错误

    c# - 在 RGB 和 HSB 颜色值之间切换的算法

    r - 用多行突出显示ggplot中的一行

    r - 如何在R中将两位数显示为绘图上的点?

    r - 固定 alpha 比例 ggplot2

    language-agnostic - 8bit YUV、10bit YUV、10bit RGB 都以RGB 等色彩空间结束。 YUV为什么存在?我为什么要使用它?

    html - 两层导航栏不正确的颜色和间距