r - ggplot中的非矩形图例
问题描述
我怎么能产生一个不是矩形的图例ggplot
?例如,我怎样才能得到圆(ish)角而不是这些尖角?
每个人都知道他们,但这里有一个例子:
ggplot(baseball, aes(year, r)) +
geom_point(aes(col=g))
会不会有类似的东西:ggplot2 中的圆角?也许工作?
解决方案
链接帖子中提到的特定策略可能会失败,因为颜色条没有被参数化为矩形,而是作为栅格。然后,另一种策略是在角落附近绘制白色的倒四分之一圆。
一种方法是定义您自己的颜色条类,并添加一些绘制这些白色角的代码。下面的代码应该适用于垂直彩条。
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 创建
推荐阅读
- apollo - ApolloQueryResult 是可变的吗?
- r - 根据以前的值更新列值(一次处理总是处理)
- ios - 防止标签栏项目的视图占用先前访问视图的方向
- javascript - 无法将画布导出为图像
- javascript - 检查字母组合是否出现在随机单词序列中并确定它们的确切位置的功能
- node.js - IMAP Node.js 执行两次,两次保存电子邮件并且不会保存来自发射器的电子邮件
- javascript - 在Javascript中获取两个数组对象的差异
- linear-programming - 将逻辑约束转换为 python 纸浆代码
- php - 使用 f_open 的 PHP 管道数据
- python - pynput 不让 tkinter 创建窗口