有时更容易编辑使用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](https://i.stack.imgur.com/QgAk1.png)
什么如果要求键是点而不是字母?它可能很有用,因为'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](https://i.stack.imgur.com/fukI9.png)
更新
考虑到@ 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,尽管OP应该评估它是否真的值得。 – BrodieG
BrodieG - 作为OP我同意你的看法,但我试图回应审稿人在手稿中的要求,因为有超过2个等级的因素和文字颜色可能会引起误解。也许有更好的方式来绘制这个。我会仔细看看的。 –