2

嗨,我正在尝试在 R 中为我的闪亮应用程序绘制一个饼图,我想将悬停数字格式化为 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

在这里你可以看到悬停数字是 1,112,201 我想要这个 1.1M 或者如果数字小于一百万假设数字是 125,463 那么当我们将鼠标悬停在饼图上时它应该是 125.5K

先感谢您

4

1 回答 1

2

要实现自定义悬停标签,您可以为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

在此处输入图像描述

这也有效:

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>")
于 2020-10-12T08:25:32.210 回答