Dan
Dan

Reputation: 5369

Plot superscripts in ggplot without losing leading zeroes

Q: how do I plot superscripted text in ggplot but not lose leading zeroes?

Problem

Goal. I am trying to plot text labels with superscripted information. The superscript is the last two digits of the year of an observation (e.g., 2018 is "18", 2005 is "05").

Problem. I can almost get this plot working correctly, but ggplot swallows the leading zeroes. For example: the superscript "18" plots correctly as "18," but the superscript "05" plots incorrectly as "5".

Example

Here's a toy example:

## libraries
library(dplyr)
library(ggplot2)

## example data
Dat <-
    tribble(~ state, ~ year, ~ x, ~ y,
            "MI",    2010,   1,   1,
            "CA",    2005,   2,   2,
            "NY",    2011,   3,   3,
            "AK",    2003,   4,   4,
            "IL",    2012,   5,   5)

## create the label: state with a superscripted year (e.g., MI^10, AK^03)
Dat$lab <-
    with(Dat,
         paste(state,
               "^{",
               substr(as.character(year), 3, 4),
               "}",
               sep = ""))

## plot the labels: note that the 0s in the superscripts disappear
ggplot(Dat,
       aes(x     = x,
           y     = y,
           label = lab)) +
    geom_text(parse = TRUE) +
    theme_bw()

It produces the following plot:

example plot showing the problematic superscripts

Note that MI, NY, and IL are plotted correctly with two-digit superscripts, but CA and AK incorrectly have single-digit superscripts. How do I keep the leading zeroes?

Upvotes: 1

Views: 224

Answers (1)

qdread
qdread

Reputation: 3953

All you need to do is add quotes around the number to be superscripted when you are pasting the expression together. This will format the number as a string inside the expression so that the leading zeroes will be retained. You can use the escape character \ to add double quotes to the already double quoted string. Edit the "create the label" portion of your code as follows:

Dat$lab <-
  with(Dat,
       paste(state,
             "^{\"",
             substr(as.character(year), 3, 4),
             "\"}",
             sep = ""))

I tested this with ggplot2 2.2.1 just now and it works.

Upvotes: 1

Related Questions