这里有两种方法可以控制图例中 grobs 的绘制顺序,但这两种方法都不简单。
第一个使用ggplot的gtable。布局数据框中的“z”列给出了绘制 grobs 的顺序。但是为了操纵图例的 grobs,必须访问图例本身的布局数据框。像这样的:
library(ggplot2)
library(gtable)
library(grid)
df = read.table(text =
"School Year Value
A 1998 5
B 1999 10
C 2000 15
A 2000 7
B 2001 15
C 2002 20", sep = "", header = TRUE)
p <- ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
geom_point(aes(colour = Species, shape = Species), size = 2) +
geom_smooth()
# Get the ggplot grob
gt <- ggplotGrob(p)
# Get the legend
leg <- gt$grobs[gt$layout$name == "guide-box"][[1]]$grobs[[1]]
# Check the layout
leg$layout
第 4 行和第 5 行绘制第一个图例键,但它先绘制点 (key-3-1-1),然后绘制线段 (key-3-1-2)。交换 z 值将确保首先绘制线段,然后绘制点。同样,对于第 7 行和第 8 行以及第 10 行和第 11 行。
# Swap the z-values for the relevant lines in the layout table
leg$layout[c(4:5, 7:8, 10:11), "z"] <- c(5:4, 8:7, 11:10)
# Put legend back into ggplot grob
gt$grobs[gt$layout$name == "guide-box"][[1]]$grobs[[1]] <- leg
# Draw it
grid.newpage()
grid.draw(gt)
第二种方法使用网格的编辑功能来改变顺序。
# Get the ggplot grob
gt <- ggplotGrob(p)
# Get the legend grob
leg = getGrob(grid.force(gt), gPath("guides"), grep = TRUE)
# Get a list of grobs (in the legend).
# This also gives the order.
grid.ls(grid.force(leg))
# Nearly the same names for the grobs,
# and the same order as before
# (don't count the indented grobs).
# Change the order in which grobs are drawn
leg = reorderGrob(leg, c(5:4, 8:7, 11:10), back = FALSE)
# Remove the original legend and replace with the new legend
gt = removeGrob(grid.force(gt), "guides", grep = TRUE)
gt = addGrob(gt, leg, "guide-box", grep = TRUE)
# Draw the plot
grid.newpage()
grid.draw(gt)