gpt4 book ai didi

r - 如何在 R Plotly 饼图和折线图中相应地将数字格式悬停为 K 或 M

转载 作者:行者123 更新时间:2023-12-04 08:46:03 28 4
gpt4 key购买 nike

嗨,我正在尝试在 R 中为我 Shiny 的应用程序绘制饼图,我想在其中将悬停数字格式化为 K 或 M,但无法找到正确的解决方案
这是我正在使用的可重现代码,任何帮助将不胜感激

full_data<-data.frame("Name"=c("Q1","Q1","Q2","Q2","Q3","Q3"),"Values"=c(245645,866556,26440,65046,641131,463265))

desc<-full_data%>%group_by(Name)%>%summarise(values=sum(Values))

fig<-plot_ly(desc,labels=~Name,values=~values,type = "pie",
insidetextfont = list(color = 'white'),
marker = list(colors = colors,
line = list(color = '#FFFFFF', width = 1),hoverformat = ',.0f'))%>%
layout(title = list(text='<b> Volume(lbs.) </b>',x=0,y=1,titlefont=20),
font=list(family="Corbel",size=15,color="rgb(33,33,33"),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
legend=list(font=list(size=18)),
margin = list(pad = 10,t=60))

fig
Here you can see hover number is 1,112,201
我想要的是 1.1M 或者如果数字小于一百万,假设数字是 125,463 那么当我们将鼠标悬停在饼图上时它应该是 125.5K
先感谢您

最佳答案

要实现自定义悬停标签,您可以向 customdata 提供向量。具有所需格式的参数并定义适当的 hovertemplate .
要获得所需的格式,您可以使用 scales::label_number_si :

library(plotly)

desc <- full_data %>%
group_by(Name) %>%
summarise(values = sum(Values)) %>%
mutate(lab = scales::label_number_si(accuracy = 0.1)(values))

desc
# A tibble: 3 x 3
Name values lab
<chr> <dbl> <chr>
1 Q1 1112201 1.1M
2 Q2 91486 91.5K
3 Q3 1104396 1.1M

plot_ly(desc,
customdata = desc$lab, #pass the lab vector
labels = ~Name,
values = ~values,
type = "pie",
insidetextfont = list(color = 'white'),
marker = list(colors = colors,
line = list(color = '#FFFFFF', width = 1),
hoverformat = ',.0f'),
hovertemplate = "%{label} <br> %{customdata} <br> %{percent}") #define hovertemplate
enter image description here
这也有效:
plot_ly(desc,
customdata = ~lab,
labels = ~Name,
values = ~values,
type = "pie",
insidetextfont = list(color = 'white'),
marker = list(colors = colors,
line = list(color = '#FFFFFF', width = 1),
hoverformat = ',.0f'),
hovertemplate = "%{label} <br> %{customdata} <br> %{percent}")
去除烦人的 trace 0在悬停中添加 <extra></extra> :
plot_ly(desc,
customdata = ~lab,
labels = ~Name,
values = ~values,
type = "pie",
insidetextfont = list(color = 'white'),
marker = list(colors = colors,
line = list(color = '#FFFFFF', width = 1),
hoverformat = ',.0f'),
hovertemplate = "%{label} <br> %{customdata} <br> %{percent} <extra></extra>")

关于r - 如何在 R Plotly 饼图和折线图中相应地将数字格式悬停为 K 或 M,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64313173/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com