A few possibilities.
annotate() . x hjust, y . : .
, . grid. grob annotation_custom(). ymin ymax . xmin xmax , .
, . , .
. 2, -grob grid. , gtable, grob ( ).
library(ggplot2)
library(grid)
library(gtable)
label = "Mean of Sepal.Width = 3.05"
myplot = ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
geom_line() +
annotate("text", x = Inf, y = 2.9, label = label, hjust = -0.08, size = 3) +
theme(plot.margin = unit(c(.5,6,.5,.5),"lines"),
legend.background = element_rect(colour = "black"))
g = ggplotGrob(myplot)
g$layout$clip[g$layout$name == "panel"] = "off"
grid.draw(g)
textgrob = textGrob(label, gp = gpar(cex = .75), )
width = unit(1, "grobwidth",textgrob) + unit(10, "points")
height = unit(1, "grobheight", textgrob)+ unit(10, "points")
rectgrob = rectGrob(gp=gpar(colour = "black", fill = NA), height = height, width = width)
labelGrob = gTree("labelGrob", children = gList(rectgrob, textgrob))
myplot = ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
geom_line() +
annotation_custom(labelGrob,
xmin = 1.137*max(iris$Sepal.Length), xmax = 1.137*max(iris$Sepal.Length),
ymin = 2.9, ymax = 2.9) +
theme(plot.margin = unit(c(0.5, 6, 0.5, 0.5), "lines"),
legend.background = element_rect(colour = "black"))
g = ggplotGrob(myplot)
g$layout$clip[g$layout$name == "panel"] = "off"
grid.draw(g)
label = "Mean of\nSepal.Width = 3.05"
myplot = ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
geom_line() +
theme(legend.background = element_rect(colour = "black"))
g = ggplotGrob(myplot)
leg = g$grobs[[which(g$layout$name == "guide-box")]]
xpos = 5
textgrob = textGrob(x = unit(xpos, "points"), label, gp = gpar(cex = .75), just = "left")
width = unit(1, "grobwidth",textgrob) + unit(2*xpos, "points")
height = unit(1, "grobheight", textgrob)+ unit(2*xpos, "points")
rectgrob = rectGrob(x = unit(0, "points"), just = "left",
gp = gpar(colour = "black", fill = NA), height = height, width = width)
labelGrob = gTree("labelGrob", children = gList(rectgrob, textgrob))
pos = subset(leg$layout, grepl("guides", name), t:r)
leg = gtable_add_rows(leg, height, pos = pos$t+1)
leg = gtable_add_grob(leg, labelGrob, t = pos$t+2, l = pos$l)
leg$widths[pos$l] = max(width, leg$widths[pos$l])
leg$heights[pos$t+1] = unit(5, "pt")
g$grobs[[which(g$layout$name == "guide-box")]] = leg
g$widths[g$layout[grepl("guide-box", g$layout$name), "l"]] = max(width, sum(leg$widths))
grid.newpage()
grid.draw(g)
