Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Updated</strong> <code>opts()</code> has been replaced with <code>theme()</code></p> <p>In the code below, a base plot is drawn, with a wider margin at the bottom of the plot. The textGrob is created, then inserted into the plot using annotation_custom(). Except the text is not visible because it is outside the plot panel - the output is clipped to the panel. But using baptiste's code <a href="https://stackoverflow.com/questions/9690648/point-clipped-on-x-axis-in-ggplot">from here</a>, the clipping can be overrridden. The position is in terms of data units, and both text labels are centred. </p> <pre><code>library(ggplot2) library(grid) # Base plot df = data.frame(x=seq(1:10), y = seq(1:10)) p = ggplot(data = df, aes(x = x, y = y)) + geom_point() + ylim(0,10) + theme(plot.margin = unit(c(1,1,3,1), "cm")) p # Create the textGrobs Text1 = textGrob(paste("Largest x-value is", round(max(df$x), 2), sep = " ")) Text2 = textGrob(paste("Mean = ", mean(df$x), sep = "")) p1 = p + annotation_custom(grob = Text1, xmin = 4, xmax = 4, ymin = -3, ymax = -3) + annotation_custom(grob = Text2, xmin = 8, xmax = 8, ymin = -3, ymax = -3) p1 # Code to override clipping gt &lt;- ggplotGrob(p1) gt$layout$clip[gt$layout$name=="panel"] &lt;- "off" grid.draw(gt) </code></pre> <p><img src="https://i.stack.imgur.com/xzUxq.png" alt="enter image description here"></p> <p>Or, using <code>grid</code> functions to create and position the label.</p> <pre><code>p grid.text((paste("Largest x-value is", max(df$x), sep = " ")), x = unit(.2, "npc"), y = unit(.1, "npc"), just = c("left", "bottom"), gp = gpar(fontface = "bold", fontsize = 18, col = "blue")) </code></pre> <p><img src="https://i.stack.imgur.com/1Bn7P.png" alt="enter image description here"></p> <p><strong>Edit</strong> Or, add text grob using gtable functions.</p> <pre><code>library(ggplot2) library(grid) library(gtable) # Base plot df = data.frame(x=seq(1:10), y = seq(1:10)) p = ggplot(data = df, aes(x = x, y = y)) + geom_point() + ylim(0,10) # Construct the text grob lab = textGrob((paste("Largest x-value is", max(df$x), sep = " ")), x = unit(.1, "npc"), just = c("left"), gp = gpar(fontface = "bold", fontsize = 18, col = "blue")) gp = ggplotGrob(p) # Add a row below the 2nd from the bottom gp = gtable_add_rows(gp, unit(2, "grobheight", lab), -2) # Add 'lab' grob to that row, under the plot panel gp = gtable_add_grob(gp, lab, t = -2, l = gp$layout[gp$layout$name == "panel",]$l) grid.newpage() grid.draw(gp) </code></pre> <p><a href="https://i.stack.imgur.com/mEo6M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mEo6M.png" alt="enter image description here"></a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload