ggplotly:悬停时重命名工具提示

Afi*_*ari 2 r ggplot2 plotly ggplotly r-plotly

在此处输入图片说明

我有一个如上图所示的图表。可重用代码如下。

plotly::ggplotly(ggplot(dplyr::as_tibble(rnorm(1000)), aes(value)) + stat_ecdf(geom = 'line'))
Run Code Online (Sandbox Code Playgroud)

我想在悬停时重命名和格式化工具提示。例如,x 轴或“价值”(在图表中)可以是“单位价格?” 而 y 轴是累积分布。

因此,当我将鼠标悬停在线上时,我希望能够看到如下所示的内容

累积分布:78.2%

单价:?0.81

谢谢!

Sté*_*ent 8

这是一种方法。

library(plotly)
library(scales) # for the number() function

gg <- ggplot(dplyr::as_tibble(rnorm(1000)), aes(value)) + 
  stat_ecdf(geom = 'line')

ggly <- ggplotly(gg)

text_x <- number(
  ggly$x$data[[1]]$x,
  prefix = "Unit Price: $",
  accuracy = 0.01
)

text_y <- number(
  ggly$x$data[[1]]$y,
  scale = 100,
  accuracy = 0.1,
  prefix = "Cumul. distribution: ",
  suffix = "%"
)

ggly %>%
  style(text = paste0(text_x, "</br></br>", text_y), traces = 1) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明