如何在 R 中修改连续的 ggplot 图例

jna*_*612 -2 r ggplot2 colorbar

我正在使用 ggplot 绘制南美洲平均气温的偏差图表。

为了绘制此图,我使用以下代码:

ggplot(bias.df2) +  
  geom_tile(aes(x=x, y=y, fill=pr), alpha=0.8) + 
  scale_fill_viridis(na.value="white") +
  coord_equal() +
  theme(legend.position="bottom") +
  theme(legend.key.width=unit(2, "cm"))+
  scale_color_continuous(limits=c(-10,10),breaks=brkbias)
Run Code Online (Sandbox Code Playgroud)

生成以下颜色条:

ggplot图例

但我需要颜色条看起来像这样:

毕业生传奇

我尝试修改颜色条的限制,但似乎没有任何东西可以生成我需要的那种绘图。非常感谢任何帮助解决这个问题的帮助。

编辑:我正在使用的数据可以在此 csv文件中找到。

lhs*_*lhs 5

guide_colorsteps()可以与breaks = 参数结合使用scale_fill_viridis_c(),以打印具有连续填充的离散颜色条。我们可以修改注释中链接的代码,将三角形添加到该指南中。由于您有一个水平条,因此需要水平而不是垂直移动和指向三角形。

library(ggplot2)
library(gtable)
library(grid)

bias.df2 <- read.csv("~/Downloads/data.csv")

my_triangle_colorsteps <- function(...) {
  guide <- guide_colorsteps(...)
  class(guide) <- c("my_triangle_colorsteps", class(guide))
  guide
}

guide_gengrob.my_triangle_colorsteps <- function(...) {
  # First draw normal colorsteps
  guide <- NextMethod()
  # Extract bar / colours
  is_bar <- grep("^bar$", guide$layout$name)
  bar <- guide$grobs[[is_bar]]
  extremes <- c(bar$gp$fill[1], bar$gp$fill[length(bar$gp$fill)])
  # Extract size
  width  <- guide$widths[guide$layout$l[is_bar]]
  height <- guide$heights[guide$layout$t[is_bar]]
  short  <- min(convertUnit(width, "cm",  valueOnly = TRUE),
                convertUnit(height, "cm", valueOnly = TRUE))
  # Make space for triangles
  guide <- gtable_add_cols(guide, unit(short, "cm"),
                           guide$layout$t[is_bar] - 1)
  guide <- gtable_add_cols(guide, unit(short, "cm"),
                           guide$layout$t[is_bar])

  left <- polygonGrob(
    x = unit(c(0, 1, 1), "npc"),
    y = unit(c(0.5, 1, 0), "npc"),
    gp = gpar(fill = extremes[1], col = NA)
  )
  right <- polygonGrob(
    x = unit(c(0, 1, 0), "npc"),
    y = unit(c(0, 0.5, 1), "npc"),
    gp = gpar(fill = extremes[2], col = NA)
  )
  # Add triangles to guide
  guide <- gtable_add_grob(
    guide, left, 
    t = guide$layout$t[is_bar],
    l = guide$layout$l[is_bar] - 1
  )
  guide <- gtable_add_grob(
    guide, right,
    t = guide$layout$t[is_bar],
    l = guide$layout$l[is_bar] + 1
  )
  
  return(guide)
}

ggplot(bias.df2) +  
  geom_tile(aes(x=x, y=y, fill=pr), alpha=0.8) + 
  scale_fill_viridis_c(na.value="white", limits = c(-10, 10),
                       breaks = c(-10, -7, -4, -1, -.5, .5, 1, 4, 7, 10), 
                       guide = my_triangle_colorsteps(show.limits = TRUE)) +
  coord_equal() +
  theme(legend.position="bottom") +
  theme(legend.key.width=unit(2, "cm"))
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2022 年 6 月 1 日创建(v2.0.1)