首页 > 解决方案 > 绘图上的悬停文本不正确

问题描述

所以我有一个显示实际值、建模值和错误的图。下面是相同的代码。

library(plotly)
library(ggplot2)

ab <-tibble::tribble(
  ~modeled, ~actuals, ~weekenddate,  ~err,
    501384,   481864, "2014-02-02", 19519,
    488933,   479078, "2014-02-09",  9856,
    484191,   464026, "2014-02-16", 20165,
    480443,   460339, "2014-02-23", 20104,
    482512,   464021, "2014-03-02", 18491,
    488843,   462458, "2014-03-09", 26385
  )


test_bottom <- ggplot(ab, aes(x = weekenddate, y = actuals)) +
  geom_smooth(method = "lm", se = FALSE, color = "lightgrey") +  # Plot regression slope
  geom_segment(aes(xend = weekenddate, yend = modeled), alpha = .2) +  # alpha to fade lines
  # > Alpha adjustments made here...
  geom_point(aes(color = err)) +  # Alpha mapped to abs(residuals)
  scale_color_gradient2(low = "blue", mid = "white", high = "red") +
  guides(color = FALSE) +  # Alpha legend removed
  geom_point(aes(y = modeled), shape = 1) +
  theme_bw()

ggplotly(test_bottom)


<sup>Created on 2018-10-12 by the [reprex package](https://reprex.tidyverse.org) (v0.2.1)</sup>

在此处输入图像描述

如果您看到悬停,它显示的模型值和实际值都相同。悬停应该只显示模型值,悬停时红点应该只显示实际值和错误。

如何才能做到这一点。

标签: rggplot2plotly

解决方案


一种解决方案是定义text美学,ggplot然后指定ggplotly必须text在工具提示中显示的内容。

library(plotly)
library(ggplot2)

ab <-tibble::tribble(
  ~modeled, ~actuals, ~weekenddate,  ~err,
    501384,   481864, "2014-02-02", 19519,
    488933,   479078, "2014-02-09",  9856,
    484191,   464026, "2014-02-16", 20165,
    480443,   460339, "2014-02-23", 20104,
    482512,   464021, "2014-03-02", 18491,
    488843,   462458, "2014-03-09", 26385
  )
names(ab)[4] <- "Error"

test_bottom <- ggplot(ab, aes(x = weekenddate, y = actuals, 
  text=paste0("Date:", weekenddate, "<br>Modeled:", modeled, "<br>Actuals:", actuals))) +
  geom_smooth(method = "lm", se = FALSE, color = "lightgrey") +
  geom_segment(aes(xend = weekenddate, yend = modeled), alpha = .2) +  
  geom_point(aes(color = Error)) +  
  scale_color_gradient2(low = "blue", mid = "white", high = "red") +
  guides(color = FALSE) + 
  geom_point(aes(y = modeled), shape = 1) +
  theme_bw()

ggplotly(test_bottom, tooltip=c("text","Error"))

在此处输入图像描述


推荐阅读