简体   繁体   English

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

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

I have gone through this , this and some other similar posts.我经历过这个这个和其他一些类似的帖子。 They all give the solution in javascript which I am unable to port to python.他们都用javascript给出了我无法移植到python的解决方案。 Help would be appreciated.帮助将不胜感激。

When I pass a value to customdata which is big enough to be a billion, it shows the sign as G (for giga) rather than B, whereas plotly defaults to B, the comparison can be seen in the image.当我将一个值传递给足够大到 10 亿的customdata ,它将符号显示为 G(表示千兆)而不是 B,而 plotly 默认为 B,可以在图像中看到比较。 Is there a way to use B instead of G?有没有办法使用 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}')

This is not going to be the most elegant solution ever but it fixes your problem.这不会是有史以来最优雅的解决方案,但它可以解决您的问题。 If you look carefully your plot you have a problem on index 1 too where the overdata is 3000<br>3k .如果您仔细查看您的绘图,您在索引 1 上也有问题,其中超量数据为3000<br>3k

So I'm actually writing hover data explicitly.所以我实际上是在明确地编写悬停数据。 We will need the function human_format from here .我们将需要这里的函数human_format

Data数据

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]})

Write hoverdata写入悬停数据

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)

Plot阴谋

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM