如果只有一个数据点,则无法使用 R 以 plotly 方式显示文本

Cannot display the text in plotly with R if there is only one data point

下面的代码生成了一个带有一个数据点的绘图。我设计这个图是为了能够在用户将鼠标光标移动到数据点时显示一些文本信息,但是正如图所示,这不起作用。

library(dplyr)
library(lubridate)
library(plotly)

a1 <- data.frame(
  DateTime = ymd_hms("2020-01-01 08:00:00"),
  Value = 1
)

a1 <- a1 %>%
  mutate(DateTimeText = as.character(DateTime))

p1 <- plot_ly(a1, x = ~DateTime, y = ~Value, type = "scatter", mode = "markers",
             text = ~DateTimeText,
             hovertemplate = paste(
               "<br>Date Time: %{text} </br>",
               "<br>Value: %{y} </br>",
               "<extra></extra>"))

但是,如果我提供两个数据点。该代码有效。这是一个例子。这对我来说很奇怪,因为我认为这两种情况都应该有效。请多多指教

a2 <- data.frame(
  DateTime = ymd_hms(c("2020-01-01 08:00:00", "2020-01-02 08:00:00")),
  Value = c(1, 2)
)

a2 <- a2 %>%
  mutate(DateTimeText = as.character(DateTime))

p2 <- plot_ly(a2, x = ~DateTime, y = ~Value, type = "scatter", mode = "markers",
              text = ~DateTimeText,
              hovertemplate = paste(
                "<br>Date Time: %{text} </br>",
                "<br>Value: %{y} </br>",
                "<extra></extra>"))

问题是 R 中长度为 1 的向量未正确转换为长度为 1 的 JSON 数组。这是一个已知的陷阱,因为将 R 对象转换为 JSON 时存在一些歧义,参见 https://plotly-r.com/json.html。当你有一个长度 > 1 的向量时,不会出现这种歧义。这就是你的代码在这种情况下工作的原因。

要解决此问题,请使用 asIs 函数或 I,即使用 text = ~I(DateTimeText)。试试这个:

library(dplyr)
library(lubridate)
library(plotly)

a1 <- data.frame(
  DateTime = ymd_hms("2020-01-01 08:00:00"),
  Value = 1
)

a1 <- a1 %>%
  mutate(DateTimeText = as.character(DateTime))

p1 <- plot_ly(a1, x = ~DateTime, y = ~Value, type = "scatter", mode = "markers",
              text = ~I(DateTimeText),
              hovertemplate = paste(
                "<br>Date Time: %{text} </br>",
                "<br>Value: %{y} </br>",
                "<extra></extra>"))

p1