有時更容易編輯使用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)
什麼如果要求鍵是點而不是字母?它可能很有用,因爲'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)
更新
考慮到@ 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個等級的因素和文字顏色可能會引起誤解。也許有更好的方式來繪製這個。我會仔細看看的。 –