Easily two of the most popular posts on my blog are this one and this one describing a couple of ways in which I managed to hack together using an image as a category label in a ggplot.
There are likely many people who believe one should never do such a thing, but given the popularity, it seems a lot of people aren’t listening to that. Good on you.
via GIPHY
One of these posts was recently shared again by the amazing #rstats amplifier Mara Averick (if you’re not following her on Twitter, you’re missing out) and @baptiste_auguie (the saviour of the previous implementation) mentioned that he had written a ‘hack’ to get chemical symbols as a categorical axis label using tikzDevice
. That package leverages
(of which I am very familiar, having written my PhD thesis entirely in
many moons ago) to treat all of the text in an image as potential
commands and produce a working source code which generates the required plot.
The example code is straightforward enough
and produces this
annotation.png
This got me curious, though — if it can process arbitrary
, could it process a \\includegraphics
call?
Yes, as it turns out.
via GIPHY
A quick test showed that it was indeed possible, which only leaves re-implementing the previous posts’ images using this method.
I’ve done so, and the code isn’t particularly shorter than the other method.
``
Producing nearly the same end result.
tikzDevice result
There are a few differences compared to the previous version(s):
– I had a request for rotating the additional text, which I actually also updated recently, and it seemed to fit better, so I rotated the labels within the command.– Since all of the text has been rendered via , the fonts are a bit different.– The rankings have since changed, so I’ve added an 11th to keep Australia in the list.
The
component of this also meant that a few changes were necessary in the other labels, such as the dollar sign in the y-axis label, and the underscores throughout (these are considered special characters in
). Lastly, the result of running the tikz
command is that a .tex
(
source code) file is produced. This isn’t quite the plot image file we want. It does however have the commands to generate one. The last steps in the above gist are to process this .tex
file with
. Here I used the tools::texi2dvi
function, but one could also use a system
command to their
installation.
That still only produced a PDF. The last step was to use the magick
package to convert this into an image.
Overall, this is a nice proof of concept, but I don’t think it’s a particularly tidy way of achieving the goal of image axis labels. It does however lay the groundwork for anyone else who decides this might be a useful route to take. Plus I learned a bit more about how tikzDevice
works and got to revisit my
knowledge.
Related