将geom_text中的图例文字颜色与符号匹配 [英] Match legend text color in geom_text to symbol
问题描述
我尝试使用 geom_text
将图例的文本与由因式分解变量生成的文本颜色匹配。这是一个最小的工作示例:
pre $ df < - data.frame(a = rnorm(10),b = 1: 10,c =字母[1:10],d = c(one,two))
pre>
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 c(one,two),
labels = c(应该是粉红色的,应该是蓝色的))
p1
我相信它是一个简单的修复。任何建议或参考以前的职位将有所帮助。我没有找到任何具体的东西。
继上述joran的评论之后,您可以直接编辑grobs。这是一个相当丑陋的代码,所以道歉[使用 grid
命令将会有更加优雅的方式来做到这一点 - 希望有人会发布]。
library(grid)
gglabcol< -
function(plot1)
g < - ggplotGrob(plot1)
#legend grobs
gb< - g [[grobs]] [[which(g $ layout $ name ==guide-box)]]
l < - gb [[grobs]] [[1]] [[grobs]]
#符号(提取颜色)
lg < - l [sapply(l,function(i)grepl(GRID.text,i))]
#为图例标签获取grobs
lb < - l [sapply(l,function(i)grepl(guide.label,i))]
#将标签颜色改变为符号颜色
for(i in seq_along(lg)){
lb [[i]] $ gp $ col < - lg [[i]] $ gp $ col
GB [[ grobs]] [[1]] [[ grobs]] [sapply(GB [[ grobs]] [[1]] [[克obs]],
函数(i)grepl(guide.label,i))] [[i]] < - lb [[i]]
}
#覆盖原始图例
g [[grobs]] [[其中(g $ layout $ name ==guide-box)]]< - gb
网格。 (g)
隐形(g)
}
Plot
gglabcol(p1)
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.
Following on from joran's comment above, you can edit the grobs directly. This is a rather ugly bit of code so apologies [there will be a much more elegant way to do this using grid
commands - and hopefully someone will post].
library(grid)
gglabcol <-
function(plot1)
{
g <- ggplotGrob(plot1)
# legend grobs
g.b <- g[["grobs"]][[which(g$layout$name=="guide-box")]]
l <- g.b[["grobs"]][[1]][["grobs"]]
# get grobs for legend symbols (extract colour)
lg <- l[sapply(l, function(i) grepl("GRID.text", i))]
# get grobs for legend labels
lb <- l[sapply(l, function(i) grepl("guide.label", i))]
# get change colour of labels to colour of symbols
for(i in seq_along(lg)) {
lb[[i]]$gp$col <- lg[[i]]$gp$col
g.b[["grobs"]][[1]][["grobs"]][sapply(g.b[["grobs"]][[1]][["grobs"]],
function(i) grepl("guide.label", i))][[i]] <- lb[[i]]
}
# overwrite original legend
g[["grobs"]][[which(g$layout$name=="guide-box")]] <- g.b
grid.draw(g)
invisible(g)
}
Plot
gglabcol(p1)
这篇关于将geom_text中的图例文字颜色与符号匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!