在 ggplot2 中添加边框或背景以缩放图例 guide_colorbar

Adding border or background to scale legend guide_colorbar in ggplot2

我在 ggplot 图表中有一个从白色到红色的颜色条,白色边框在白色背景上不是很明显。

有没有办法对图例中的刻度线进行不同的着色或在渐变比例周围添加边框?

这是一个最小的例子:

df <- data.frame(x <- rnorm(10),
                 y <- rnorm(10),
                 fill <- rnorm(10))

ggplot(df, aes(x, y, fill = fill)) + 
  geom_point() + 
  scale_fill_gradient(low = 'white', high = 'red')

使用 element_rectfill 参数找到了解决我的问题的方法。

df <- data.frame(x <- rnorm(10),
                 y <- rnorm(10),
                 fill <- rnorm(10))

ggplot(df, aes(x, y, fill = fill)) + 
  geom_point() + 
  scale_fill_gradient(low = 'white', high = 'red') + 
  theme(legend.background = element_rect(fill = "grey95"))

我更喜欢颜色条周围的边框,但这似乎不可能...

在最新的 ggplot2(开发版,将发布为 2.3)中,现在可以工作了:

# devtools::install_github("tidyverse/ggplot2") # do this once
library(ggplot2)
df <- data.frame(x <- rnorm(10),
                 y <- rnorm(10),
                 fill <- rnorm(10))

ggplot(df, aes(x, y, fill = fill)) + 
  geom_point() + 
  scale_fill_gradient(low = 'white', high = 'red',
    guide = guide_colorbar(frame.colour = "black", ticks.colour = "black"))