Data precision using geom_dl() in ggplot

I’m using ggplot and gganimate to create an animation of time series data. Specifically, I’m using geom_dl() with the method “last.points” to display the data at the evolving end of the time series plot. I can’t figure out how to set the precision of the data label to always be 3 digits after the decimal point, in other words to not truncate when the last digit is a zero. Can anyone help me with this? Thank you!

basic advice; is explicitly determine what your labels should be and make a specific variable for that; you can use helpful tools like scales::comma to dictate precision.

example:

library(babynames)
library(tidyverse)
library(gganimate)
library(directlabels)

# Keep only 3 names
don <- babynames %>% 
  filter(name %in% c("Ashley")) %>%
  filter(sex=="F") |> 
  mutate(faken = n/123,
         mylabel=scales::comma(faken,accuracy=0.001))

# Plot
don %>%
  ggplot( aes(x=year, y=faken, group=name, color=name,
              label=mylabel)) +
  geom_line() +
  geom_point() +
  scale_color_discrete() +
  ggtitle("Popularity of American names in the previous 30 years") +
  ylab("Number of babies born dividided by 123 :) ") +
  geom_dl(method = "last.points") +
  transition_reveal(year)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.