我如何格式化plot.ly' text'这样的一美元金额(或其他任何东西) - $ 4,000,000(用逗号) - 在R?
即使我的真实'数据已格式化为$,一旦我执行hoverinfo =' x + text'在add_trace函数中,它会丢失格式。 Hoverformat =" $,f"在情节布局功能中也没有帮助。
以下是堆叠区域图中R的可重现示例:
library(plotly)
season <- c('Winter', 'Spring', 'Summer', 'Fall')
y1_real<- c(40, 80, 95, 10)
y2_real<- c(20, 55, 10, 10)
y3_real<- c(40, 10, 60, 180)
df= data.frame(season, y1_real, y2_real, y3_real)
#changing the format of the real data to $
class(df$y1_real)<- c("money", class(df$y1_real) )
class(df$y2_real)<- c("money", class(df$y2_real))
class(df$y3_real)<- c("money", class(df$y3_real))
df$y3_stck<- df$y3_real + df$y2_real + df$y1_real
df$y2_stck<- df$y2_real + df$y1_real
df$y1_stck<- df$y1_real
p1<- plot_ly(df, x=season, y=y1_stck, text=df$y1_real, hoverinfo='x+text+name', name="Blue", fill="tonexty")
p2<- add_trace(p1, x=season, y=y2_stck, text=df$y2_real, hoverinfo='x+text+name', name="Orange", fill="tonexty")
p3<- add_trace(p2, x=season, y=y3_stck, text=df$y3_real, hoverinfo='x+text+name', name="Green", fill="tonexty")
p4<- layout(yaxis=list(showgrid=FALSE, showline=FALSE, hoverformat="$,f"))
p4
谢谢!
答案 0 :(得分:4)
这是一个建议:-) 创建三个带有美元符号的新列。
df$y1_reald <- paste(y1_real, "$", sep="")
df$y2_reald <- paste(y2_real, "$", sep="")
df$y3_reald <- paste(y3_real, "$", sep="")
并在text参数中使用这三个新列。你会看到$显示
p1<- plot_ly(df, x=season, y=y1_stck, text=df$y1_reald, hoverinfo='x+text+name', name="Blue", fill="tonexty")
p2<- add_trace(p1, x=season, y=y2_stck, text=df$y2_reald, hoverinfo='x+text+name', name="Orange", fill="tonexty")
p3<- add_trace(p2, x=season, y=y3_stck, text=df$y3_reald, hoverinfo='x+text+name', name="Green", fill="tonexty")
p4<- layout(yaxis=list(showgrid=FALSE, showline=FALSE, hoverformat="$,f"))
p4
编辑:在评论中提出问题
几乎相同的代码,只是将您的列乘以能够为您提供所需数字的数字并添加&#34;,&#34;用于分隔符。
y1_reald <- (y1_real*100000)
y2_reald <- (y2_real*100000)
y3_reald <- (y3_real*100000)
y1_reald <- prettyNum(y1_reald,big.mark=",",scientific=FALSE)
y2_reald <- prettyNum(y2_reald,big.mark=",",scientific=FALSE)
y3_reald <- prettyNum(y3_reald,big.mark=",",scientific=FALSE)
#
df$y1_reald <- paste(y1_reald, "$", sep="")
df$y2_reald <- paste(y2_reald, "$", sep="")
df$y3_reald <- paste(y3_reald, "$", sep="")
然后运行
p1<- plot_ly(df, x=season, y=y1_stck, text=df$y1_reald, hoverinfo='x+text+name', name="Blue", fill="tonexty")
p2<- add_trace(p1, x=season, y=y2_stck, text=df$y2_reald, hoverinfo='x+text+name', name="Orange", fill="tonexty")
p3<- add_trace(p2, x=season, y=y3_stck, text=df$y3_reald, hoverinfo='x+text+name', name="Green", fill="tonexty")
p4<- layout(yaxis=list(showgrid=FALSE, showline=FALSE, hoverformat="$,f"))
p4
将为您提供所需的图表。