簡體   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