Search code examples
pythonplotly

Bar chart plot shows linearly increasing data


Using Python plotly, the charted data shows linearly increasing data, but is not correct. Also, the first data point (i.e. 5585) is rendered as empty bar. How do I fix these?

import plotly.graph_objects as go
fig = go.Figure()

x = df_quaterly_results.index 
y = df_quaterly_results[df_quaterly_results.columns[0]]  # Sales Columns

trace_name = 'QoQ Sales'

fig.add_trace(go.Bar(x=x, y=y, name=trace_name))

plot_title = 'QoQ Sales'

fig.update_layout(
        title=plot_title,
        xaxis_title='Quarter',
        yaxis_title='Rupees in Cr.')

# pyo.plot(fig, filename="temp-plot.html")
fig.show()

enter image description here

Sample Dataframe:

Quarter Sales
Jun 2021 5585
Sep 2021 7096
Dec 2021 8527
Mar 2022 7893
Jun 2022 8607
Sep 2022 8458

Note: The column Quarter is dataframe index here.


Solution

  • The issue suggests that the 'Sales' column in your dataframe contains strings, in which case Plotly uses a categorical axis.

    You just need to convert df_quaterly_results['Sales'] or at least y to the proper type, eg.

    y = df_quaterly_results['Sales'].astype(int)
    

    Sample dataframe plotted with categorical axis :

    categorical

    Sample dataframe plotted with numerical axis :

    numerical