如何添加美元符号悬停?

How to add dollar signs to hover?

这是我正在使用的代码:

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>")

当您将鼠标悬停在图表上时,我试图在“值”之前包含美元符号。看起来我现在在代码中所做的事情不起作用。有人知道我做错了什么吗?

例如:价值:$4851.20

我知道怎么做了。它可能不是最有效的。如果您认为有更好的方法可以做到这一点,请告诉我。这个 特别有用。注意:有关于此示例的可重现性的评论。此数据来自库 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')

快速说明:如果您想要 space 在 $ 和您悬停的数字之间(即 $ 489.5),您可以使用 paste() 而不是 paste0( ) 在 mycurrency 函数中。由你决定。

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"
)