gpt4 book ai didi

r - 将 geom_text 中的图例文本颜色与符号匹配

转载 作者:行者123 更新时间:2023-12-04 01:46:46 29 4
gpt4 key购买 nike

我正在尝试将图例的文本与使用 geom_text 的因子变量生成的文本颜色进行颜色匹配.这是一个最小的工作示例:

df <- data.frame(a=rnorm(10),b=1:10,c=letters[1:10],d=c("one","two"))
p1 <-ggplot(data=df,aes(x=b,y=a))
p1 <- p1 + geom_text(aes(label = c, color=d, fontface="bold"))
p1 <- p1 + scale_color_hue(name="colors should match",breaks=c("one", "two"),
labels=c("should be pink", "should be blue"))
p1

enter image description here

我相信这是一个简单的修复。任何建议或引用以前的帖子都会有所帮助。我没有找到任何具体的内容。

最佳答案

这是一个使用 ggtext 的解决方案并避免直接编辑 grobs。 (它确实涉及从图中提取颜色,但后续步骤更加用户友好。)

# Original code, but with a stripped-down call to `scale_color_hue` (since
# we're going to replace it).
library(ggplot2)
df <- data.frame(a=rnorm(10),b=1:10,c=letters[1:10],d=c("one","two"))
p1 <-ggplot(data=df,aes(x=b,y=a))
p1 <- p1 + geom_text(aes(label = c, color=d, fontface="bold"))
p1 <- p1 + scale_color_hue(breaks=c("one", "two"))

# Load the `ggtext` library, which lets us style (parts of) text labels.
library(ggtext)
# Build the plot so we can extract the colors that were actually used. (If you
# supply colors manually instead, this step isn't necessary.)
g1 = ggplot_build(p1)
# Add a scale with labels that are colored appropriately, using <span> tags.
# Also specify that legend labels should be processed with `element_markdown`.
p1 +
scale_color_hue(name = "colors should match",
breaks = c("one", "two"),
labels = paste("<span style='color:",
unname(unlist(unique(g1$data[[1]]["colour"]))),
"'>",
c("should be pink", "should be blue"),
"</span>",
sep = "")) +
theme(legend.text = element_markdown())

enter image description here

关于r - 将 geom_text 中的图例文本颜色与符号匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23588127/

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