将 geom_text 中的图例文本颜色与符号匹配 [英] Match legend text color in geom_text to symbol

查看:23
本文介绍了将 geom_text 中的图例文本颜色与符号匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to color match the text of the legend to the color of text produced by a factored variable using geom_text. Here is a minimal working example:

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

我相信这是一个简单的修复.任何建议或对先前帖子的引用都会有所帮助.我没有找到任何特定于此的东西.

I am sure its a simple fix. Any suggestions or reference to prior posts would help. I did not find anything specific to this.

推荐答案

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

Here's a solution that uses ggtext and avoids editing grobs directly. (It does involve extracting the colors from the plot, but the subsequent steps are more user-friendly.)

# 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())

这篇关于将 geom_text 中的图例文本颜色与符号匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆