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

如果只有一个数据点,则无法使用R以绘图方式显示文本,r,plotly,r-plotly,R,Plotly,R Plotly,代码将生成一个带有一个数据点的绘图仪。我设计这个图是为了在用户将鼠标光标移动到数据点时能够显示一些文本信息,但正如图所示,这不起作用 library(dplyr) library(lubridate) library(plotly) a1 <- data.frame( DateTime = ymd_hms("2020-01-01 08:00:00"), Value = 1 ) a1 <- a1 %>% mutate(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 = ~DateTimeText,
             hovertemplate = paste(
               "<br>Date Time: %{text} </br>",
               "<br>Value: %{y} </br>",
               "<extra></extra>"))
库(dplyr)
图书馆(lubridate)
图书馆(绘本)

a1问题在于,R中的长度为1的向量没有正确转换为长度为1的JSON数组。这是一个已知的陷阱,因为将R对象转换为JSON时存在一些歧义,请参阅。当向量长度大于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 
库(dplyr)
图书馆(lubridate)
图书馆(绘本)
a1
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