将标签放置在binned/stepcolorbarguide中的bin中间?

推理:我想轻松使用现成的连续尺度(来自任何提供scale_..._continuous等的包),用于有序因子类数据,例如mtcars$cyl. 因为这些数据只包含几种离散值,我想直接标记图例键,而不是 bin 限制。怎么做?

library(ggplot2)

ggplot(mtcars, aes(mpg, disp, color = cyl))+
  geom_point() +
  scale_color_continuous(limits = range(mtcars$cyl),
                         guide = guide_colorsteps(ticks.colour = "black"))

不想要的:

hacky 方式,实际上是四个 (!) hacks,并且是不想要的。

# Hack 1 - create the colors manually from the palette. This is already annoying. 
cont_col <- colorRampPalette(c("#132B43","#56B1F7"))(length(unique(mtcars$cyl)))

# Hack 2- you need to modify the underlying draw_key function 
# from https://github.com/tidyverse/ggplot2/issues/2844
draw_key_polygon2 <- function(data, params, size) {
  lwd <- min(data$size, min(size) / 4)
  grid::rectGrob(
    width = grid::unit(1, "npc"),
    height = grid::unit(1, "npc"),
    gp = grid::gpar(
      col = data$colour,
      fill = alpha(data$fill, data$alpha),
      lty = data$linetype,
      lwd = lwd * .pt,
      linejoin = "mitre"
    ))
}

# Hack 3 discretise the variable
ggplot(mtcars, aes(mpg, disp, color = as.character(cyl))) +
  geom_point(key_glyph = "polygon2") +
  scale_color_manual(values = cont_col) +
# Hack 4 override aes to change the fill of the key glyph polygons
  guides(color = guide_legend(override.aes = list(fill = cont_col))) 

但这会导致所需的输出

由reprex 包( v2.0.0 )于 2021 年 5 月 2 日创建

回答

这是我能想到的最简单的方法。

  1. 将填充设置为after_scale(colour)与矩形键一起使用。
  2. 将中断设置为文字值并使用图例指南。
library(ggplot2)

ggplot(mtcars, aes(mpg, disp, color = cyl)) +
  geom_point(aes(fill = after_scale(colour)), # set fill for rect key
             key_glyph = draw_key_rect) + # rect key
  scale_colour_continuous(
    breaks = sort(unique(mtcars$cyl)),
    guide = guide_legend()
  )

由reprex 包(v1.0.0)于 2021 年 5 月 2 日创建


以上是将标签放置在binned/stepcolorbarguide中的bin中间?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>