首页 > 解决方案 > ggplot中的非矩形图例

问题描述

我怎么能产生一个不是矩形的图例ggplot?例如,我怎样才能得到圆(ish)角而不是这些尖角?

每个人都知道他们,但这里有一个例子:

ggplot(baseball, aes(year, r)) +
  geom_point(aes(col=g))

在此处输入图像描述

会不会有类似的东西:ggplot2 中的圆角?也许工作?

标签: rggplot2tidyverse

解决方案


链接帖子中提到的特定策略可能会失败,因为颜色条没有被参数化为矩形,而是作为栅格。然后,另一种策略是在角落附近绘制白色的倒四分之一圆。

一种方法是定义您自己的颜色条类,并添加一些绘制这些白色角的代码。下面的代码应该适用于垂直彩条。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.5
library(grid)

# Custom constructor, just tags on another class
my_round_colourbar <- function(...) {
  guide <- guide_colourbar()
  class(guide) <- c("my_round_colourbar", class(guide))
  guide
}

# Customised drawing code that adds the corners
guide_gengrob.my_round_colourbar <- function(...) {
  # Use the usual drawing method
  grob <- NextMethod()
  # Find the bar from the normal legend
  is_bar <- grep("bar", grob$layout$name)[[1]]
  bar <- grob$grobs[[is_bar]]
  # Measure the bar
  width  <- convertUnit(bar$width, "cm", valueOnly = TRUE)
  height <- convertUnit(bar$height, "cm", valueOnly = TRUE)
  minor <- min(width, height)
  # Draw 'caps': 2 inverted corner pieces
  t <- seq(0, pi, length.out = 180)
  cap <- data.frame(
    x = c((cos(t) / 2), -0.5, 0.5) * minor,
    y = c((-sin(t) / 2) + 0.5, 0, 0) * minor
  )
  # Draw a polygon for each cap
  bottom <- polygonGrob(x = unit(cap$x, "cm") + bar$x, 
                        y = unit(cap$y, "cm") + bar$y - 
                          unit(height * 0.5, "cm"), 
                        gp = gpar(fill = "white",col = NA),
                        default.units = "cm")
  top <- polygonGrob(x = unit(cap$x, "cm") + bar$x, 
                     y = unit(-cap$y, "cm") + bar$y + unit(height * 0.5, "cm"),
                     gp = gpar(fill = "white", col = NA),
                     default.units = "cm")
  # Add polygon to bar
  bar <- grobTree(bar, top, bottom)
  grob$grobs[[is_bar]] <- bar
  return(grob)
}

ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(colour = drat)) +
  guides(colour = my_round_colourbar())

reprex 包(v1.0.0)于 2021-07-05 创建


推荐阅读