有时使用编辑 grob 会更容易grid
的编辑功能 - 如果可以找到相关 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”一组 grobs 中 - 名称以“label”开头。有两个GRUB:
标签-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)
如果要求按键是点而不是字母怎么办?它可能很有用,因为“a”是图中的符号,也是图例键中的符号。这不是像上面那样简单的编辑。我需要一个点 grob 来代替文本 grob。我在视口中绘制对象,但是如果我可以找到相关视口的名称,那么进行更改应该很简单。
# Find the names of the relevant viewports
current.vpTree() # Scroll out to the right to find he relevant 'key' viewports.
视口[key-4-1-1.5-2-5-2], 视口[key-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)
Update
考虑到 @user20650 更改图例键的建议(请参阅下面的评论):
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
然后像以前一样继续更改图例文本的颜色。