這是我正在使用的代碼:
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
uj5u.com熱心網友回復:
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"
)
uj5u.com熱心網友回復:
我想出了如何做到這一點。它可能不是最有效的。如果您認為有更好的方法可以做到這一點,請告訴我。這個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() 。它是由你決定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/329910.html
上一篇:使用R中ggplot2的facet_wrap功能對多個資料集進行Boxplot比較?
下一篇:ggplot,分兩類的條形圖
