r语言 - 如何添加美元符号悬停?



下面是我使用的代码:

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

我试图在"值"之前包含美元符号。当你将鼠标悬停在图表上时。似乎我现在在代码中所做的工作不起作用。有人知道我哪里做错了吗?

示例:value: $4851.20

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

我知道该怎么做了。它可能不是最有效的。如果你认为有更好的方法,请告诉我。这个stackoverflow问题特别有帮助。注意:有一个关于这个例子的可重复性的评论。此数据来自库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()。这取决于你。

相关内容

  • 没有找到相关文章

最新更新