Search code examples
rdatetimeggplot2posixctlegend-properties

Fixed ggplot legend position using datetime axis?


I want to place a legend inside a ggplot. The x-axis however, is in datetime while the y-axis is numeric. In theme() I can neither use c(0, 0) to place the legend to the origin of the plot, nor can I use a combination c(some datetime value, some numeric value). Any suggestions?

\ time like 2018-12-03 13:00:00 is "POSIXct" \ column is "chr" \ total_As_out is "num"

ggplot(data = col_outflow, mapping = aes(x = time, y = total_As_out, colour = column, shape = column)) +
  geom_point(na.rm = TRUE) +
  geom_line(data = col_outflow[!is.na(col_outflow$total_As_out),], na.rm = TRUE) +
  scale_color_manual(values = cols) +
  scale_shape_manual(values = c(5, 15, 5, 15, 5, 15)) +
  ylab("As outflow [µg/l]") +
  theme(
    axis.title.x = element_blank(),
    legend.justification = c(0,1),
    legend.position = c(min(col_outflow$time), 15)
  )

the code above gives Error in (function (el, elname) : Element legend.position must be a string or numeric vector.


Solution

  • I've found that I can indeed give a numeric vector to legend.position. The values just have to be in [0, 1], not the actual values displaied on the axis.