0

I'm creating a Bar Chart with the top 10 highest amounts for each zip code. I've converted the zip code to a string, but in the Bar Chart the x axis is showing as an int 20K, 50K, etc. When checking the astype on zip code it return object type instead of string. I'm confused. How do I show the zip code on the x axis (i.e. '95519', '47905', '44720')?

Bar Chart

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)
user3066155
  • 157
  • 2
  • 2
  • 15
  • Can you provide a minimal example of df3? Maybe `df3.head()`, or `df3.head().to_dict()`? `px.bar` - what is `px`? Please read [mre]. – wwii May 29 '20 at 13:55
  • Related: [Plotly: How to set values for major ticks / gridlines for x-axis?](https://stackoverflow.com/questions/55160390/plotly-how-to-set-values-for-major-ticks-gridlines-for-x-axis) – wwii May 29 '20 at 14:11
  • I added Dataset of df3. px.bar is express. (i.e. import plotly.express as px). I have also used grah objects as well but get the same issue. import plotly.graph_objects as go – user3066155 May 29 '20 at 16:09

1 Answers1

1

If you add fig.update_xaxes(type='category') your code will work, as this ensures that the zip code is treated as categorical rather than numerical.

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()

enter image description here

mad
  • 320
  • 1
  • 11
Flavia Giammarino
  • 7,987
  • 11
  • 30
  • 40