Putting labels for only the first and the last value of data in R and ggplot2

Hi!!

i have made a graph that looks like this:
image

And I would like to know how I can put labels on the first and last value of my data on each scatter plot line without having a fixed data set since every month this data gets renewed and i want to have a general code for the graph.
Thank you so much!

Consider something along these lines:

frmLast <- frmData %>% # last trading day
  slice(which.max(Date))

frmFirst <- frmData %>% # first trading day
  slice(which.min(Date))

This code will create two new data.frames, with frmFirst having the first record and frmLast having the last record from the original frame (it assumes that trade date is in field Date).

The special treatement (in my case big red ending point & label) can be relatively easily combined with a ggplot of the full series programmatically.

Consider this piece of code (it requires {Quandl}, but the underlying data does not truly matter).


frmData <- Quandl("BCHARTS/BITSTAMPUSD") %>%
  select(Date, Close) %>%
  filter(Date >= as.Date('2018-07-01')) %>% 
  mutate(Value = 10000 / Close)

frmLast <- frmData %>% # last trading day
  slice(which.max(Date))

frmFirst <- frmData %>% # first trading day
  slice(which.min(Date))


ggplot(data = frmData, aes(x = Date, y = Value)) +
  geom_line(col = "red", size = 1.25) +
  # last trading day - round mark, annotation below
  geom_point(data = frmLast, aes(x = Date, y = Value), col = "red", shape = 21, fill = "white", size = 2, stroke = 1.7) +
  geom_text(data = frmLast, aes(x = Date, y = Value, label = sprintf("%0.3f", round(Value, digits = 3))), size = 4, vjust = 2.5) +
  # first trading day - round mark, annotation above
  geom_point(data = frmFirst, aes(x = Date, y = Value), col = "red", shape = 21, fill = "white", size = 2, stroke = 1.7) +
  geom_text(data = frmFirst, aes(x = Date, y = Value, label = sprintf("%0.3f", round(Value, digits = 3))), size = 4, vjust = -1.5) +
  scale_x_date(labels = date_format("%d-%b-%y")) +
  expand_limits(x = frmFirst$Date, y = .5) +
  scale_y_continuous(labels = dollar_format(prefix = "", suffix = " BTC")) + #, expand = c(0, 0)) +
  ggtitle("Bitcoin value of a $10,000 investment") +
  theme(axis.title = element_blank())

2 Likes

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