R中的数字可以格式化而不丢失数字class吗?
Can numbers in R be formatted without losing numeric class?
我正在用 ggplolty 制作图表,当鼠标悬停在条形图上时,您可以看到 y 变量的值,在我的例子中这是一个很大的数字。
我知道使用 ggplot 可以有单独的列,一列用于获取图表上的值,另一列用于格式化标签。所以使用格式函数我得到字符不是问题。
所以问题是是否可以将数字 100000000 格式化为 100 000 000
它保持数字状态,因此可以绘制条形图,并且 plotly 标签将显示格式正确的数字
library(ggplot2)
library(plotly)
library(scales)
# here you can see numbers on chart after hover not nicely formatted
df<-data.frame(x=letters[1:6],y=runif(6,120000000,130000000))
ggplotly(ggplot(df,aes(x=x,y=y))+geom_bar(stat="identity"))
# and this unfortunately formats well but converts to character
df$y<-format(df$y,big.mark = " ")
class(df$y)
对于悬停文本:
tmp <- ggplot(df,aes(x=x,y=y))+geom_bar(stat="identity")
p <- plotly_build(tmp)
p$data[[1]]$text <-prettyNum(df$y, big.mark = " ")
p
我正在用 ggplolty 制作图表,当鼠标悬停在条形图上时,您可以看到 y 变量的值,在我的例子中这是一个很大的数字。
我知道使用 ggplot 可以有单独的列,一列用于获取图表上的值,另一列用于格式化标签。所以使用格式函数我得到字符不是问题。
所以问题是是否可以将数字 100000000 格式化为 100 000 000 它保持数字状态,因此可以绘制条形图,并且 plotly 标签将显示格式正确的数字
library(ggplot2)
library(plotly)
library(scales)
# here you can see numbers on chart after hover not nicely formatted
df<-data.frame(x=letters[1:6],y=runif(6,120000000,130000000))
ggplotly(ggplot(df,aes(x=x,y=y))+geom_bar(stat="identity"))
# and this unfortunately formats well but converts to character
df$y<-format(df$y,big.mark = " ")
class(df$y)
对于悬停文本:
tmp <- ggplot(df,aes(x=x,y=y))+geom_bar(stat="identity")
p <- plotly_build(tmp)
p$data[[1]]$text <-prettyNum(df$y, big.mark = " ")
p