2014-05-11 49 views
10

我试图使用geom_text将因数文本的颜色与因子变量生成的文本颜色相匹配。下面是一个最小的工作例如:将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

我相信它是一个简单的解决。任何建议或参考以前的职位将有所帮助。我没有找到任何具体的东西。

回答

11

从上面joran的评论继,你可以直接编辑grobs。这是一个相当丑陋的代码,所以很抱歉[使用grid命令将会有更好的方式来做到这一点 - 希望有人会发布]。

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) 
    } 

情节

gglabcol(p1) 


enter image description here

+3

+1,尽管OP应该评估它是否真的值得。 – BrodieG

+0

BrodieG - 作为OP我同意你的看法,但我试图回应审稿人在手稿中的要求,因为有超过2个等级的因素和文字颜色可能会引起误解。也许有更好的方式来绘制这个。我会仔细看看的。 –

3

图中的颜色与图例中的颜色相同,但即使将图形符号fontface设置为粗体(或斜体),图例字体仍保持原样。我不确定这是否是ggplot2的设计或预期行为的疏忽。对于某些颜色,粗体字体看起来比普通字体更饱和,使其看起来像不同的颜色。

在任何情况下,这是一个混乱比grobs更容易,但这可能会让你想要什么。使用geom_text与纯字体,但连续两次或三次(或更多),所以你会得到overplotting。这将使符号和图例看起来类似于粗体字体,因为两者都将被叠加,并且图例符号将总是与剧情符号相同。

下面是一个例子:

library(ggplot2) 
library(gridExtra) 

# Original plot (with larger font size) 
p1 <- ggplot(data=df) + 
    geom_text(aes(x=b, y=a, label=c, color=d), fontface='bold', size=8) 
p1 <- p1 + scale_color_hue(name="colors should match",breaks=c("one", "two"), 
           labels=c("should be pink", "should be blue")) + 
      ggtitle("Original Plot with Bold Symbols and Plain Legend") 

# New version with overplotting. (You don't need to specify 'plain' fontface. 
# I've just included that to emphasize what the code is doing.) 
p1.overplot <- ggplot(data=df) + 
    geom_text(aes(x=b, y=a, label=c, color=d), fontface='plain', size=8) + 
    geom_text(aes(x=b, y=a, label=c, color=d), fontface='plain', size=8) + 
    geom_text(aes(x=b, y=a, label=c, color=d), fontface='plain', size=8) 
p1.overplot <- p1.overplot + 
    scale_color_hue(name="colors should match", 
        breaks=c("one", "two"), 
        labels=c("should be pink", "should be blue")) + 
    ggtitle("Both symbols and legend are overplotted 3 times") 

enter image description here

+0

感谢这个漂亮的技巧来匹配字体的脸部,但 - 我实际上是试图匹配传奇文字,“应该是粉红色的”和“应该是蓝色的”,以图例和情节符号。 例如,文本“应该是粉红色的”应该带有与字母'a','c','e','g'和'i'相同的颜色,而文本“应该是蓝色的”必须是相同的颜色为'b','d','f','h'和'j' –

+0

嗯,我想我需要在下次更仔细地阅读这个问题! – eipi10

+0

@ eipi10,这个问题不容易理解,OP应该写''“这个传奇文字字体应该是粉红色的'''。在阅读了上述评论的前半部分之后,我认为他希望将文本“应该是粉红色的”打印在情节中。我想可能性是无止境的:-)你的kludge对我来说实际上是非常有用的! – PatrickT

4

有时更容易编辑使用grid的编辑功能GROB - 如果能找到相关grobs的名字。在这种情况下,可以找到它们,并且编辑很简单 - 将标签的颜色从黑色更改为红色或蓝色。

library(ggplot2) 
library(grid) 

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 salmon", "should be sky blue")) 
p1 

# Get the ggplot grob 
g <- ggplotGrob(p1) 

# Check out the grobs 
grid.ls(grid.force(g)) 

查看grobs列表。我们想要编辑的grobs是在名单的底部,在'guide-box'集合中,名称以“label”开头。有两种grobs:

标签3-3.4-4-4-4
标签4-3.5-4-5-4

# Get names of 'label' grobs. 
names.grobs <- grid.ls(grid.force(g))$name 
labels <- names.grobs[which(grepl("label", names.grobs))] 

# Get the colours 
# The colours are the same as the colours of the plotted points. 
# These are available in the ggplot build data. 
gt <- ggplot_build(p1) 
colours <- unique(gt$data[[1]][, "colour"]) 

# Edit the 'label' grobs - change their colours 
# Use the `editGrob` function 
for(i in seq_along(labels)) { 
    g <- editGrob(grid.force(g), gPath(labels[i]), grep = TRUE, 
     gp = gpar(col = colours[i])) 
} 

# Draw it 
grid.newpage() 
grid.draw(g) 

enter image description here

什么如果要求键是点而不是字母?它可能很有用,因为'a'是情节中的一个符号,它是图例关键中的一个符号。这不是一个简单的编辑,就像上面一样。我需要一个点grob来代替文本grob。我在视口中绘制了grobs,但是如果我能找到相关视口的名称,则应该直接进行修改。

# Find the names of the relevant viewports 
current.vpTree() # Scroll out to the right to find he relevant 'key' viewports. 

视[密钥4-1-1.5-2-5-2],视[密钥3-1-1.4-2-4-2],

# Well, this is convenient. The names of the viewports are the same 
# as the names of the grobs (see above). 
# Easy enough to get the names from the 'names.grobs' list (see above). 
# Get the names of 'key' viewports(/grobs) 
keys <- names.grobs[which(grepl("key-[0-9]-1-1", names.grobs))] 

# Insert points grobs into the viewports: 
# Push to the viewport; 
# Insert the point grob; 
# Pop the viewport. 
for(i in seq_along(keys)) { 
    downViewport(keys[i]) 
    grid.points(x = .5, y = .5, pch = 16, gp = gpar(col = colours[i])) 
    popViewport() 
} 
popViewport(0) 

# I'm not going to worry about removing the text grobs. 
# The point grobs are large enough to hide them. 

plot = grid.grab() 
grid.newpage() 
grid.draw(plot) 

enter image description here

更新

考虑到@ user20650的建议改变罪nd键(请参阅下面的注释):

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 salmon", "should be sky blue")) 

GeomText$draw_key <- function (data, params, size) { 
    pointsGrob(0.5, 0.5, pch = 16, 
    gp = gpar(col = alpha(data$colour, data$alpha), 
    fontsize = data$size * .pt)) } 

p1 

然后按照以前一样继续更改图例文本的颜色。

+1

@ user20650非常感谢您的支持。这非常有用。 –

+1

是的,它的一个不错的新功能 - 羞愧的标签不是那么容易 – user20650

相关问题