Dan Chaltiel
Dan Chaltiel

Reputation: 8484

y-axis scale as percents in ggplotly

I'm using scale_y_continuous to format my y-axis in percentage:

library(ggplot2)
ggplot(tibble(x=c(0,5,10),y=c(0,0.5,0.75)), aes(x=x,y=y)) + 
  geom_point() + 
  scale_y_continuous(limits=c(0,1), labels=scales::percent)

plotly::ggplotly()

However, how can I keep this format in the plotly tooltip (which shows y as floats)?

Upvotes: 3

Views: 363

Answers (1)

Gi_F.
Gi_F.

Reputation: 961

You can access the tooltip text as

ply$x$data[[1]]$text

So the code below might be useful

library(ggplot2)
pl = ggplot(dplyr::tibble(x=c(0,5,10),y=c(0,0.5,0.75)), aes(x=x,y=y)) + 
geom_point() + 
scale_y_continuous(limits=c(0,1), labels=scales::percent)

ply = plotly::ggplotly(pl)

tip = ply$x$data[[1]]$text
tip = do.call('c', lapply(strsplit(tip, 'y:'), function(x){paste0(x[1], 'y:',paste0(x[2], '%'))}  ))
ply$x$data[[1]]$text = tip

Edit - put it in a function

prc_ggplotly = function(pl = ggplot2::last_plot(), i = 1)
{
  ply = plotly::ggplotly(pl)

  if(any(grepl('%', ply$x$layout$yaxis$ticktext)))
  {
    tip = ply$x$data[[i]]$text
    tip = do.call('c', lapply(strsplit(tip, 'y:'), function(x) {paste0(x[1], 'y:',paste0(x[2], '%'))}  ))
    ply$x$data[[i]]$text = tip
  }

  if(any(grepl('%', ply$x$layout$xaxis$ticktext)))
  {
    tip = ply$x$data[[i]]$text
    tip = do.call('c', lapply(strsplit(tip, '<'), function(x) { paste0(paste0(x[1], '%'), '<', x[2])}  ))
    ply$x$data[[i]]$text = tip
  }

  return(ply)
}

Hope this helps

Upvotes: 3

Related Questions