Home > Enterprise >  How to add dollar signs to hover?
How to add dollar signs to hover?

Time:10-22

Here is the code that I'm using:

library(ggplot2)
library(plotly)

 ggplotly(ggplot(economics_long, aes(date, value))  
      geom_line()  
      facet_wrap(vars(variable), scales = "free_y", ncol = 1, strip.position = "top")  
      theme(strip.background = element_blank(), strip.placement = "outside"), hoverinfo = "text", hovertext = "value: %{value:$.2f}<br>")

I'm trying to include dollar sign before the "value" when you hover over the graphs. It seems like what I'm doing right now in the code isn't working. Anyone know what I'm doing wrong?

For example: value: $4851.20

CodePudding user response:

library(ggplot2)
library(plotly)

ggplotly(
  ggplot(
    economics_long, 
    aes(
      date, 
      value, 
      group = 1,
      text = paste0("value: $", sprintf("%.2f", value))
    )
  )  
    geom_line()  
    facet_wrap(vars(variable), scales = "free_y", ncol = 1, strip.position = "top")  
    theme(strip.background = element_blank(), strip.placement = "outside"), 
  tooltip = "text"
)

CodePudding user response:

I figured out how to do this. It may not be the most efficient. If you believe that there is a better way to do this, please let me know. This stackoverflow question was especially helpful. Note: there was a comment about the reproducibility of this example. This data comes from the dataset in the library ggplot2.

## created function to convert value in economics_long as a currency
mycurrency <- function(x){
  return(paste0("$", formatC(as.numeric(x), format="f", digits=2, big.mark=",")))
}

## added text to the aes along with grouping by variable
## notice that the column that is being grouped will be the same as the data colum being included in the facet
g <- ggplot(economics_long, aes(x= date, y=value, text = paste('value: ', mycurrency(value), '<br>Date: ', as.Date(date)), group = variable))  
  facet_wrap(vars(variable), scales = "free_y", ncol = 1, strip.position = "top")  
  geom_line()  
  theme(strip.background = element_blank(), strip.placement = "outside")

## running ggplotly with tooltip as text
ggplotly(g, tooltip ='text')

Quick note: If you want space between $ and the number in your hover (i.e. $ 489.5), you could use paste() instead of paste0() in the mycurrency function. It is up to you.

  • Related