Plotly 条形图未在 x 轴上正确显示邮政编码
Plotly Bar Chart Not showing Zip Code Correctly on xaxis
我正在创建一个条形图,其中包含每个邮政编码的前 10 个最高金额。我已将邮政编码转换为字符串,但在条形图中,x 轴显示为 int 20K、50K 等。检查邮政编码上的 astype 时,它 return 对象类型而不是字符串。我很困惑。 如何在 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)
如果您添加 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()
我正在创建一个条形图,其中包含每个邮政编码的前 10 个最高金额。我已将邮政编码转换为字符串,但在条形图中,x 轴显示为 int 20K、50K 等。检查邮政编码上的 astype 时,它 return 对象类型而不是字符串。我很困惑。 如何在 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)
如果您添加 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()