ggplot2中的圆角?

11

感觉这应该是可能的,但我无法确定是否可以在theme()中相对简单地完成,还是需要更深入的挖掘。

我想在我的ggplot2图形的绘图区域上圆角。我该如何实现?

问题灵感来自:https://twitter.com/Hoog10HK/status/951305194809143296


1
有人之前已经采用了“这感觉不对”的方法:https://www.r-bloggers.com/rounded-corners-in-ggplot2-graphics/ - Jon Harmon
Mmm:element_rect 的一个版本,它带有一些额外的选项来控制圆角,并切换到 grid.roundedRect(或者可能是由 gTree 包装的)似乎是直观的方法。 - jimjamslam
1
@rensa 我需要深入了解 element_rect 实际返回的内容。如果可能在其中加入圆角而不破坏其余使用该返回值的函数,那肯定是可行的。 - Jon Harmon
1
@rensa:element_rect只是一个数据结构,你不能让它绘制圆角矩形。 - Claus Wilke
2个回答

20

您可以将背景的物体替换为圆角矩形:

library(ggplot2)
library(grid)

# make a plot with blue background
p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() +
  theme(plot.background = element_rect(fill = "#C4E7FF"),
        panel.background = element_blank(),
        plot.margin = margin(20, 20, 20, 20))

# switch out background grob
g <- ggplotGrob(p)
bg <- g$grobs[[1]]
round_bg <- roundrectGrob(x=bg$x, y=bg$y, width=bg$width, height=bg$height,
                          r=unit(0.1, "snpc"),
                          just=bg$just, name=bg$name, gp=bg$gp, vp=bg$vp)
g$grobs[[1]] <- round_bg

# draw both plots side by side
cowplot::plot_grid(p, g, labels = c("rectangular", "rounded"),
                   scale = 0.85, hjust = 0.5, label_x = 0.5)

如果您希望绘图其他方面也是圆角的,比如面板背景、图例背景等,可以应用相同的技巧。

输入图像描述


我想我们可能有点过度设计这个问题了;我忘了你可以在绘图后直接进去修改grobs! - jimjamslam

8
由于ggplot2 v3.0.0中的主题元素子类化,我能够在github包中实现了更普遍的方法,使用elementalist::element_rect_round()。(免责声明: 我编写了该github包)
library(ggplot2)
library(elementalist) # devtools::install_github("teunbrand/elementalist")

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
  geom_point() +
  facet_grid(~ cyl) +
  theme(
    legend.background = element_rect_round(radius = unit(0.2, "snpc")),
    legend.key = element_rect_round(radius = unit(0.4, "snpc")),
    panel.background = element_rect_round(radius = unit(1, "cm")),
    strip.background = element_rect_round(radius = unit(8, "pt")),
    plot.background  = element_rect_round(fill = "#C4E7FF")
  )

此内容由reprex package (v1.0.0)于2021-07-05创建


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接