Alex
Alex

Reputation: 23

nudge a label on a time-axis in ggplot

I would like to add and nudge a text label in ggplot, but nudge_x when x is POSIXct class does not change anything, no matter the value. Sample code here:

library(ggplot2)

start.time <- c("7:00", "8:00", "9:30")
end.time <- c("10:00", "11:00", "13:30")
market <- c("Name1", "Name2", "Name3")

df <- data.frame(market, start.time, end.time)

df$start.time <- as.POSIXct(df$start.time, format="%H:%M")
df$end.time <- as.POSIXct(df$end.time, format="%H:%M")
df$length <- df$end.time - df$start.time


ggplot(df) +
  geom_segment(aes(x = start.time, xend = end.time, 
               y = market, yend = market), 
           color = "darkgreen", size = 2) +
  geom_text(aes(x = min(start.time), y = market, label = length), 
        hjust = 0, size = 3, color = "darkgreen", nudge_x = -1)

Creates this image:

test plot

I would like the labels for the length of the lines to be further to the left. I do not think nudge_x = -1 is registering because it is not the correct class.

Thanks!

Upvotes: 2

Views: 3135

Answers (2)

eipi10
eipi10

Reputation: 93851

As another option, you could put the labels inside the segments. For example:

library(dplyr)

ggplot(df) +
  geom_segment(aes(x = start.time, xend = end.time, 
                            y = market, yend = market), 
               color = "darkgreen", size = 5) +
  geom_text(data=df %>% group_by(market) %>% 
              summarise(xval=mean(c(end.time, start.time)),
                        length=paste(length, "hours")),
            aes(x = xval, y = market, label = length), 
            size = 3, color = "white") + 
  labs(x="Time") + theme_bw()

enter image description here

Upvotes: 2

Sandipan Dey
Sandipan Dey

Reputation: 23109

On datetime scale nudge_x=-1 shifts to left by 1 sec, which is not visible, may be you want to nudge by 1 hr (3600 secs):

ggplot(df) +
  geom_segment(aes(x = start.time, xend = end.time, 
                   y = market, yend = market), 
               color = "darkgreen", size = 2) +
  geom_text(aes(x = min(start.time), y = market, label = length), 
            hjust = 0, size = 3, color = "darkgreen", nudge_x = -3600)

enter image description here

To nudge by 15 mins use to nudge_x = -15*60

Upvotes: 1

Related Questions