✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Barchart ignoring text x-values

Hi,
Could I please ask someone to help me understand this one…

I have a dataframe like this:

image

I’m giving it to the bar chart like this:

fig = px.bar(df_percent, x="peoplecnt", y="Percentage", color='Wave', barmode='group',
             height=400)
fig.show()

But when it displays… the barchart is missing two bars… the ‘None’ and the ‘Over 5’

So, can anyone help me ? Just need to get all seven bars displayed??
Why would the barchart be ignoring the text values of peoplecnt??

Thanks in advance

Is it because they are not integers?

Hi @adamschroeder
Yep, it was that… but I couldn’t figure out WHY.
Seems to me that plotly charts try to make inferences about the data.
Pretty smart normally… but in this case it just siezes on the numerical ones…

Anyway… turns out there is a setting for it…


fig.update_layout(xaxis_type='category',
                  title_text='Bar chart with categorical axes')

So, great, now I have

But I had to do a little bit more to get the ordering of the categories the way I wanted…

Here’s the full code…

fig = px.bar(df_percent, x="peoplecnt", y="Percentage", color='Wave', barmode='group',
             height=400)
# force plotly to treat x as categorical data
fig.update_layout(xaxis_type='category',
                  title_text='People outside household face to face')
# tell plotly what order we want the categories in 
fig.update_xaxes({'categoryorder':'array',
                            'categoryarray' : ("None", "1","2","3","4","5","Over 5")
                           })
fig.show()

Just in case anyone is having the same problem with the Radar chart (radar plot, spider plot)

This is how I did it…


import plotly.graph_objects as go

categories = ['1','2','3',
              'None', 'More than 3']

fig = go.Figure()

fig.add_trace(go.Scatterpolar(
      r=[1, 5, 2, 2, 3],
      theta=categories,
      fill='toself',
      name='Product A'
))
fig.add_trace(go.Scatterpolar(
      r=[4, 3, 2.5, 1, 2],
      theta=categories,
      fill='toself',
      name='Product B'
))

fig.update_layout(
  polar=dict(
    radialaxis=dict(
      visible=True,
      range=[0, 5],
    ),
    angularaxis=dict(
        type='category'
    )
  ),
  showlegend=False
)

fig.show()

Hope this helps someone… :slight_smile:

1 Like