繁体   English   中英

如何在ggplot时间序列中添加值标签

[英]How to add value labels in ggplot time series

如何在 ggplot 时间序列图中添加具有相应值的标签?

我试过了,但没有成功...

library(ggplot2)
library(ggrepel)
library(dplyr)
library(plotly)

set.seed(1234)

df <- data.frame(
  dates = c(
    "2022-01-01",
    "2022-01-02",
    "2022-01-03",
    "2022-01-04",
    "2022-01-05",
    "2022-01-06",
    "2022-01-07",
    "2022-01-08",
    "2022-01-09",
    "2022-01-10",
    "2022-01-11",
    "2022-01-12",
    "2022-01-13",
    "2022-01-14",
    "2022-01-15",
    "2022-01-16",
    "2022-01-17",
    "2022-01-18",
    "2022-01-19",
    "2022-01-20"
  ),
  yhat  = rnorm(20, 0, 1),
  realv = rnorm(20, 0, 1)
) %>%
  mutate(
    dates = as.Date(dates)
  )

通过使用 plotly,我尝试了...

ggplotly(
  ggplot(df, aes(x = dates)) + 
    geom_line(aes(y = yhat), color = "red") +
    geom_line(aes(y = realv), color = "black")  +
    
    geom_text_repel(data = df, aes(dates, yhat, label = realv)) 

)

我尝试使用geom_text(aes(label = as.character(yhat_final)), size = 7)添加标签,但它也没有用..

根据警告消息 geom_text_repel 尚未在 plotly 中实现。

警告消息:在 geom2trace.default(dots[[1L]][[1L]],dots[[2L]][[1L]],dots[[3L]][[1L]]) 中:geom_GeomTextRepel() 尚未在 plotly 中实现。 如果你想看到这个 geom 的实现,请在https://github.com/ropensci/plotly/issues上用你的示例代码打开一个问题

您可以使用 geom_text 并在 y 值上进行操作:

ggplotly( ggplot(df, aes(x = dates)) + 
geom_line(aes(y = yhat), color = "red") +
geom_line(aes(y = realv), color = "black")  +
geom_text(data = df, aes(dates, yhat + 0.2, label = round(realv, digits = 1))))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM