简体   繁体   English

带有 2 个直接标签的绘图条形图

[英]Plotly bar chart with 2 direct labels

I have some DataFrame to be plotted on plotly in bar chart.我有一些 DataFrame 要在条形图中绘制。

Here is a dataframe example:这是一个数据框示例:

Here is an example of dataframe这是数据框的示例

I am trying to display on graph 2 direct data labels, but can not do it anyway.我试图在图 2 上显示直接数据标签,但无论如何都做不到。 I want to show count and share separated by comma (eg "3.3M, 0.88").我想显示用逗号分隔的计数和共享(例如“3.3M,0.88”)。 Can anyone help me?谁能帮我?

Below is my code:下面是我的代码:


    import plotly.express as px
    fig = px.bar(
        df, x="range", y="count", hover_data=["share"], color="range", text="count", height=500, width=950,
        color_discrete_sequence = px.colors.sequential.Plasma_r
                )
    fig.update_layout(xaxis_type="category")
    fig.update_traces(texttemplate='%{text:.2s,  }', textposition='outside')
    pio.write_html(fig, 'cell_id.html')
    fig.show()

Here is an example of graph这是图形的示例

Thank you beforehand!先谢谢了!

I had the same problem and solved it like follows (I took your data as example):我遇到了同样的问题,解决方法如下(我以你的数据为例):

import pandas as pd
import plotly.express as px
x = [1, 2, 3, 4, 5]
y = [3300000, 290000, 88000, 40000, 57000]
df = pd.DataFrame(dict(range=['1-10', '11-20', '21-30', '31-40', '41 or above'],
                       count=[3322933, 287372, 87938, 40061, 56767], share=[0.88, 0.08, >0.02, 0.01, 0.01]))

fig = px.bar(df, x='range', y='count', hover_data=['share'], color='range',
             text=('{}, {:.2f}'.format(df['count'][0], df['share'][0]),
                   '{}, {:.2f}'.format(df['count'][1], df['share'][1]),
                   '{}, {:.2f}'.format(df['count'][2], df['share'][2]),
                   '{}, {:.2f}'.format(df['count'][3], df['share'][3]),
                   '{}, {:.2f}'.format(df['count'][4], df['share'][4])),
             height=500, width=950, color_discrete_sequence = 
px.colors.sequential.Plasma_r)

fig.update_layout(xaxis_type="category")
fig.update_traces( textposition='outside')
fig.show()

which results in the following plot:这导致以下情节: 在此处输入图片说明

So you have to add the direct labels as a list to the parameter px.bar(text=list()) and create an individual entry for every bar.因此,您必须将直接标签作为列表添加到参数 px.bar(text=list()) 并为每个条形创建单独的条目。

by changing the entries for example like this通过像这样更改条目

text=(`{}people, {:.2f}%'.format(df['count'][0], df['share'][0]*100)`, ...)

3322933people, 88%

you can add more detail information to the direct labels.您可以向直接标签添加更多详细信息。

I do not know whether there is a more elegant way to code this but this did it for me.我不知道是否有更优雅的编码方式,但这对我来说是这样的。

I hope this helps.我希望这有帮助。

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

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