繁体   English   中英

为什么对于 R 中 plotly 的某些数据点,hovertemplate 没有正确显示

[英]Why is hovertemplate not showing up correctly for some data points for plotly in R

mydat2 <- data.frame(subject = c("math", "english", "chemistry"), score = c(80, 50, 65), class = c("A", "B", "A"), count = c(50, 60, 70))

library(plotly)
plot_ly(data = mydat2,
        x = ~score,
        y = ~count,
        color = ~class,
        customdata= ~class,
        hoverinfo = 'text',
        text = ~subject,
        hovertemplate = paste(
           "<b>%{text}</b><br><br>",
           "%{yaxis.title.text}: %{y:,.0f}<br>",
           "%{xaxis.title.text}: %{x:,.0f}<br>",
           "Class: %{customdata}",
           "<extra></extra>"
        ))

在此处输入图像描述

我很困惑为什么最左边的 hover 显示为%{text}而不是english plot 上其他 2 个点的 hover 标签非常好。

这是您的图表,带有您正在寻找的 hover 模板。 解释如下。

plot_ly(data = mydat2,
        x = ~score,
        y = ~count,
        color = ~class,
        type = "scatter",
        mode = "markers",
        customdata= ~class,
        hoverinfo = 'text',
        text = ~I(subject),         # <---- I changed!!
        hovertemplate = paste(
          "<b>%{text}</b><br><br>",
          "%{yaxis.title.text}: %{y:,.0f}<br>",
          "%{xaxis.title.text}: %{x:,.0f}<br>",
          "Class: %{customdata}",
          "<extra></extra>"
        ))

在此处输入图像描述

我以前见过这个问题。 我通常会想出一个解决方法,但直到现在才真正弄清楚出了什么问题。 我在 GitHub 上找到了一张针对此问题的已关闭票证(2019 年关闭)。 (啊,是的……所以不固定。)显然,它与使用颜色有关。

然而,亮点......在激烈的一分钟内,有人实际上认为这是一个问题并提出了解决方案。 @cpsievert 编写了一些包含lapply调用的代码(如果您访问该站点,则在页面中间)。 当我调查代码的作用时,我意识到它可以简单得多(而且一开始就非常简单)。

如果您想检查一下,GitHub 上的票就在这里

这是维护者提供的代码(您实际上并不需要)。

l <- plotly_build(p)$x
l$data <- lapply(l$data, function(tr) { tr[["text"]] <- I(tr[["text"]]); tr })
as_widget(l)

修复是 function I() 而不是hovertext =text = ~subject ,您需要hovertext =text = ~I(subject) <-- 注意I()

暂无
暂无

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

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