python 中的 B(十亿)而不是 G(千兆)plotly customdata [SI 前缀 d3]

B (billions) instead of G (giga) in python plotly customdata [SI prefix d3]

我浏览了 this, 和其他一些类似的帖子。他们都在 javascript 中给出了我无法移植到 python 的解决方案。帮助将不胜感激。

当我将一个值传递给 customdata 时,该值大到十亿,它显示的符号为 G(代表千兆)而不是 B,而 plotly 默认为 B,可以看到比较在图像中。有没有办法用 B 代替 G?

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'x':[500,3000,50000,100000,7000000,80000000,400000000,9000000000]})
more_data = [100,3000,50000,600000,2000000,90000000,500000000,3000000000]

fig = px.line(df, log_y=True)
fig.update_traces(mode='lines+markers',
                  customdata=more_data,
                  hovertemplate='%{y}<br>%{customdata:,.1s}')

这不会是有史以来最优雅的解决方案,但它可以解决您的问题。如果你仔细看你的情节,你在索引 1 上也有问题,其中超数据是 3000<br>3k.

所以我实际上是在明确地编写悬停数据。我们需要 here.

中的函数 human_format

数据

import pandas as pd
import plotly.express as px
df = pd.DataFrame({'x': [500,3000,50000,100000,7000000,80000000,400_000_000,9_000_000_000],
                  'more_data': [100,3000,50000,600000,2000000,90000000,500000000,3_000_000_000]})

写入悬停数据

def human_format(num):
    num = float('{:.3g}'.format(num))
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), 
                         ['', 'K', 'M', 'B', 'T'][magnitude])

df["hover_data"] = df.apply(lambda r: 
    f"{human_format(r['x'])}<br>{human_format(r['more_data'])}",
                            axis=1)

情节

fig = px.line(df, 
              y="x", log_y=True)
fig.update_traces(mode='lines+markers',
                  customdata=df['hover_data'],
                  hovertemplate='%{customdata}')