2
votes

enter image description here

I have a plotly chart as above. Reusable code as below.

plotly::ggplotly(ggplot(dplyr::as_tibble(rnorm(1000)), aes(value)) + stat_ecdf(geom = 'line'))

I want to rename and format the tooltip on hovering. For example, x-axis or 'value' (in the chart) can be 'Unit Price in ฿' while the y-axis is the Cumul Distribution.

So when I hover on the line, I want to be able to see something like below

Cumul Distribution: 78.2%

Unit Price : ฿0.81

Thanks!

2

2 Answers

8
votes

Here is a way.

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) 

enter image description here

1
votes

You can you plotly package. Here is an article which tells you how to add a custom tooltip Plotly

Hmm, changing aes seems to be the only way we can modify the labels and it doesn't support exactly what you want right now