I'm trying to display frequencies within barplot ... well, I want them somewhere in the graph: under the bars, within bars, above bars or in the legend area. And I recall (I may be wrong) that it can be done in ggplot2
. This is probably an easy one... at least it seems easy. Here's the code:
p <- ggplot(mtcars)
p + aes(factor(cyl)) + geom_bar()
Is there any chance that I can get frequencies embedded in the graph?
geom_text
is tha analog oftext
from base graphics:If you want to adjust the y-position of the labels, you can use the
y=
aesthetic withinstat_bin
: for example,y=..count..+1
will put the label one unit above the bar.The above also works if you use
geom_text
andstat="bin"
inside.When wanting to add different info the following works:
If you are not restricted to ggplot2, you could use ?text from base graphics or ?boxed.labels from the plotrix package.
A hard way to do it. I'm sure there are better approaches.
Alternatively, I found useful to use some of the available annotation functions:
ggplot2::annotate
,ggplot2::annotation_custom
orcowplot::draw_label
(which is a wrapper ofannotation_custom
).ggplot2::annotate
is just recycling the geom text option. More advantageous for plotting anywhere on the canvas are the possibilities offered byggplot2::annotation_custom
orcowplot::draw_label
.Examples with
ggplot2::annotate
Or allow
y
to vary:Example with
ggplot2::annotation_custom
The
ggplot2::annotate
has limitations when trying to plot in more "unconventional" places, as it was asked originally ("somewhere in the graph"). However,ggplot2::annotation_custom
in combination with setting clipping off, allows annotation anywhere on the canvas/sheet, as the below example shows:Example with
cowplot::draw_label
cowplot::draw_label
is a wrapper ofggplot2::annotation_custom
, and is slightly less verbose (as a consequence). It also needs clipping off to plot anywhere on the canvas.Note that,
draw_label
can also be used in combination withcowplot::ggdraw
, switching to relative coordinates, ranging from 0 to 1 (relative to the entire canvas, see examples withhelp(draw_label)
). In that case settingcoord_cartesian(clip = "off")
is not required anymore as things are taken care byggdraw
.Created on 2019-01-16 by the reprex package (v0.2.1)