感觉这应该是可能的,但我无法确定是否可以在theme()
中相对简单地完成,还是需要更深入的挖掘。
我想在我的ggplot2
图形的绘图区域上圆角。我该如何实现?
问题灵感来自:https://twitter.com/Hoog10HK/status/951305194809143296
感觉这应该是可能的,但我无法确定是否可以在theme()
中相对简单地完成,还是需要更深入的挖掘。
我想在我的ggplot2
图形的绘图区域上圆角。我该如何实现?
问题灵感来自:https://twitter.com/Hoog10HK/status/951305194809143296
您可以将背景的物体替换为圆角矩形:
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)
如果您希望绘图其他方面也是圆角的,比如面板背景、图例背景等,可以应用相同的技巧。
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创建
element_rect
的一个版本,它带有一些额外的选项来控制圆角,并切换到grid.roundedRect
(或者可能是由gTree
包装的)似乎是直观的方法。 - jimjamslamelement_rect
只是一个数据结构,你不能让它绘制圆角矩形。 - Claus Wilke