The End of the Line

October 5, 2016
By

(This article was first published on R-SquareD, and kindly contributed to R-bloggers)

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

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)