我想在ggplot中添加并轻推一个文本标签,但是当x是POSIXct类时,nudge_x不会改变任何内容,无论值是多少。示例代码:
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)
创建此图片:
我希望线条长度的标签更靠左边。我不认为nudge_x = -1正在注册,因为它不是正确的类。
谢谢!
答案 0 :(得分:1)
在日期时间刻度上nudge_x = -1向左移动1秒,这是不可见的,可能是你要轻推1小时(3600秒):
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)
用15分钟轻推nudge_x = -15*60
答案 1 :(得分:1)
作为另一种选择,您可以将标签放在细分中。例如:
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()