【问题标题】:Plotly 条形图未在 xaxis 上正确显示邮政编码
【发布时间】:2020-09-17 02:47:11
【问题描述】:

我正在创建一个条形图,其中包含每个邮政编码的前 10 个最高金额。我已将邮政编码转换为字符串,但在条形图中,x 轴显示为 int 20K、50K 等。在检查邮政编码的 astype 时,它​​返回对象类型而不是字符串。我糊涂了。 如何在 x 轴上显示邮政编码(即“95519”、“47905”、“44720”)?

Data Set is as follows
        zip code  index
54      95519        1.70
61      81212        1.70
160     47905        1.70
421     57201        1.70
208      1930        1.69
366     44720        1.69
298     28401        1.68
532     82214        1.68
102     30165        1.67
125     50501        1.67

df3 = df2[['zip code', 'index']]
df3 = df3.nlargest(10, 'index')

 df3['zip code'] = df3[['zip code']].astype(str)


 fig = px.bar(df3, x='zip code', y='index',
         hover_data=['zip code', 'index'], color='index',
         labels={'index':'INDEX'}, height=400)

【问题讨论】:

标签: python plotly-dash


【解决方案1】:

如果您添加fig.update_xaxes(type='category'),您的代码将起作用,因为这样可以确保邮政编码被视为分类而不是数字。

import pandas as pd
import plotly.express as px

df3 = pd.DataFrame({'zip code': [95519, 81212, 47905, 57201, 1930, 44720, 28401, 82214, 30165, 50501],
                    'index': [1.70, 1.70, 1.70, 1.70, 1.69, 1.69, 1.68, 1.68, 1.67, 1.67]})

fig = px.bar(df3, x='zip code', y='index', hover_data=['zip code', 'index'], color='index', labels={'index': 'INDEX'}, height=400)

fig.update_xaxes(type='category')

fig.show()

【讨论】:

    猜你喜欢
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多