【问题标题】:How to add dollar signs to hover?如何添加美元符号以悬停?
【发布时间】:2021-12-08 08:55:45
【问题描述】:

这是我正在使用的代码:

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

【问题讨论】:

  • 不会将 unicode 用于您的字符串工作吗? “\u0024”而不是“$”
  • 我试过了,但似乎没有添加美元符号"value: %{y:\u0024.2f}&lt;br&gt;"

标签: r ggplot2 plotly ggplotly


【解决方案1】:
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"
)

【讨论】:

  • 这是一个更好的解决方案,谢谢。
【解决方案2】:

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

快速提示:如果您想在 $ 和悬停中的数字之间留有空格(即 $ 489.5),您可以在 mycurrency 函数中使用 paste() 而不是 paste0()。这取决于你。

【讨论】:

    猜你喜欢
    • 2015-07-11
    • 2014-09-10
    • 2016-12-12
    • 1970-01-01
    • 2020-01-03
    • 2022-08-22
    • 2016-04-25
    • 2021-11-22
    相关资源
    最近更新 更多