I am looking to add a small white text box, with custom text in the body of my ggplot plot. The text I want to add is to identify a horizontal line I am adding to the plot.
ggplot(cb_emp) +
geom_point(aes(x = grossunits,
y = rate,
color = as.factor(outlier))
, alpha = 1/4) +
scale_color_discrete(name ="Outcome",
breaks=c(0, 1),
labels=c("Not outlier", "Outlier")) +
geom_hline(aes(yintercept = meancbrate)) +
geom_vline(aes(xintercept = meanac) +
annotate("text", x = max(grossunits), y = meancbrate, label = "avg rate")
Here is the plot I get:
Here is the plot I want (or something like this):
Please let me know if there is an easy way of achieving this.
Greatly appreciate the help!
If you want to annotate your plot or figure with labels, there are two basic options: text() will allow you to add labels to the plot region, and mtext() will allow you to add labels to the margins. For the plot region, to add labels you need to specify the coordinates and the label.
To add labels at specified points use annotate() with annotate(geom = "text", ...) or annotate(geom = "label", ...) . To automatically position non-overlapping text labels see the ggrepel package.
Method 1: Using geom_text() This method is used to add Text labels to data points in ggplot2 plots.
Add shapes with annotate() The annotate() function allows to add all kind of shape on a ggplot2 chart. The first argument will control what kind is used: rect or segment for rectangle, segment or arrow.
You can simply change to
annotate("label", x = max(grossunits), y = meancbrate, label = "avg rate")
which will use geom_label
rather than geom_text
and so you get a rectangle around the label.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With