R | Labels inside Time Series Plot

Viewed 240

I want to plot a label (Mean Temp and Windspeed) into a Time Series Plot. My attempt works fine with "non Time-Formats" on the x-axis. But as soon as I want to plot it this way, I get the error:

Invalid input: time_trans works with objects of class POSIXct only

Example:

library(ggplot2)  
library(dplyr) 
library(glue) 
library(ggtext)     

set.seed(1700)

  
df <- data.frame(Time = seq(as.POSIXct("2012-01-01"),
                            as.POSIXct("2012-01-02"), 
                            by=(30*60)), 
                 Temp = runif(49, min=10, max=15),
                 Windsp = runif(49, min=1, max=5),  
                 Prec = runif(49, min=0, max=3))


df_label <- df  %>%
  summarize(Tmean = mean(Temp),
            Ws_mean = mean(Windsp)) %>%
  mutate(posx = 1, posy = 3,
    label = glue("Tmean = {round(Tmean, 3)} °C <br> Ws_mean = {round(Ws_mean, 3)} m/s"))  
  


ggplot(df, aes(x = Time, y = Prec)) + 
  geom_line(size = 1.5) + 
  scale_x_datetime(breaks = "2 hour",
                   minor_breaks = "1 hour",
                   date_labels = "%H:%M") +
  scale_y_continuous(breaks=seq(0,3.5,0.5)) +
  geom_richtext(
    data = df_label,
    aes(posx, posy, label = label),
    hjust = 0, vjust = 0,
    size = 3,
    # remove label background and outline
    fill = "white", label.color = "black")

I´m pretty sure

posx = 1, posy = 4,

is causing the problem, but I don´t know how to replace them.

1 Answers

The solution is much simpler than what it seems. If the x axis is in a datetime scale, and posx is to be the 1st position in that scale, set

posx = as.POSIXct("2012-01-01")

in the mutate instruction. This value is the 1st value in df$Time, created earlier. An alternative, used below, would be posx = df$Time[1].

I have also changed the vjust setting. The complete code is now

library(tidyverse)
library(glue)
library(ggtext)

set.seed(1700)

df <- data.frame(Time = seq(as.POSIXct("2012-01-01"),
                            as.POSIXct("2012-01-02"),
                            by=(30*60)),
                 Temp = runif(49, min=10, max=15),
                 Windsp = runif(49, min=1, max=5),
                 Prec = runif(49, min=0, max=3))


df_label <- df  %>%
  summarize(Tmean = mean(Temp),
            Ws_mean = mean(Windsp)) %>%
  mutate(
    posx = df$Time[1], posy = 3,
    label = glue("Tmean = {round(Tmean, 3)} °C <br> Ws_mean = {round(Ws_mean, 3)} m/s"))


ggplot(df, aes(x = Time, y = Prec)) +
  geom_line(size = 1.5) +
  scale_x_datetime(breaks = "2 hour",
                   minor_breaks = "1 hour",
                   date_labels = "%H:%M") +
  scale_y_continuous(breaks=seq(0,3.5,0.5)) +
  geom_richtext(
    data = df_label,
    aes(posx, posy, label = label),
    hjust = 0, vjust = 0.5,
    size = 3,
    # remove label background and outline
    fill = "white", label.color = "black")

enter image description here

Related