The End of the Line

[This article was first published on R-SquareD, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Adding labels to the end of lines indicating the last value –

Often, the value of the last data point in price series data is important to the viewer. Adding these yourself is always clumsy.

Value Label

I considered creating my own geom to handle these but decided to see if someone else did the work for me. The answer, kind of. The directlabels is intended to replace the legend and add labeling directly in the plot area.

library(dplyr)
library(ggplot2)
library(directlabels)
tx <- time(mdeaths)
Time <- ISOdate(floor(tx),round(tx%%1 * 12)+1,1,0,0,0)
uk.lung <- rbind(data.frame(Time,sex="male",deaths=as.integer(mdeaths)),
                 data.frame(Time,sex="female",deaths=as.integer(fdeaths)))

ggplot(uk.lung, aes(x=Time, y=deaths)) +
  geom_line(aes(color=sex)) +
  geom_dl(aes(label=sex, color=sex)
                    , method = list("last.points"))

plot of chunk unnamed-chunk-1

The geom_dl is a custom geom in the directlabels package and is easy to use. This is a nice feature and has lots of options, but I am looking for a way to show that the last data point for male is 1341 and female is 574. The package is not designed to do this, but with a small data hack, we can still use it.

tx <- time(mdeaths)
Time <- ISOdate(floor(tx),round(tx%%1 * 12)+1,1,0,0,0)
uk.lung <- rbind(data.frame(Time,sex="male",deaths=as.integer(mdeaths)),
                 data.frame(Time,sex="female",deaths=as.integer(fdeaths))) %>%
  group_by(sex) %>%
  mutate(last_value = last(deaths)) 

ggplot(uk.lung, aes(x=Time, y=deaths)) +
  geom_line(aes(color=sex)) +
  geom_dl(aes(label=last_value, color=sex)
                        , method = list("last.qp"))

plot of chunk unnamed-chunk-2

To leave a comment for the author, please follow the link and comment on their blog: R-SquareD.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)