gpt4 book ai didi

r - ggplot 从图例中删除 geom_label 边框

转载 作者:行者123 更新时间:2023-12-02 16:22:04 24 4
gpt4 key购买 nike

由于某些原因,当您使用 geom_label 时,ggplot 会向实际点添加边框,但不会在图例中包含边框。一个简单的例子:

library(tidyverse)

mtcars %>%
rownames_to_column('car') %>%
slice(1:10) %>%
ggplot(aes(cyl, mpg, label = car, col = factor(am))) +
geom_label() +
scale_x_continuous(limits = c(2, 10))

enter image description here

我希望图例中的那些小 'a' 也有红色和蓝色边框(为清楚起见,不是围绕整个图例的边框),但我不知道该怎么做。我已经探索过在 guides 函数中使用 override.aes 选项,但不知道是否可以通过这种方式添加边框。

最佳答案

正如@r2evans所说,现在很难通过简单的方式做到这一点。
我的答案是通过创建和替换函数 GeomLabel$draw_key 来实现的。
(注意:此答案基于 Change geom_text's default "a" legend to label string itself )

library(tidyverse); library(grid)

oldK <- GeomLabel$draw_key # to save for later

# define new key
# if you manually add colours then add vector of colours
# instead of `scales::hue_pal()(length(var))`
GeomLabel$draw_key <- function (data, params, size#,
# var=unique(iris$abbrev),
# cols=scales::hue_pal()(length())
) {

gr <- roundrectGrob(0.5, 0.5, width = 0.9, height = 0.9,
just = "center",
gp = gpar(col = data$colour, fill = NA))
gt <- textGrob("a", 0.5, 0.5,
just="center",
gp = gpar(col = alpha(data$colour, data$alpha),
fontfamily = data$family,
fontface = data$fontface,
fontsize = data$size * .pt))
grobTree(gr, gt)
}

mtcars %>%
rownames_to_column('car') %>%
slice(1:10) %>%
ggplot(aes(cyl, mpg, label = car, col = factor(am))) +
geom_label() +
scale_x_continuous(limits = c(2, 10))

# reset key
GeomLabel$draw_key <- oldK

enter image description here

关于r - ggplot 从图例中删除 geom_label 边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65298945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com