Search code examples
pythonpandasplotly

Plotly doesn't draw barchart from pivot


I am trying to draw a bar chart from the CSV data I transform using pivot_table. The bar chart should have the count on the y-axis and companystatus along the x-axis.

I am getting this instead: Bar chart not showing

Ultimately, I want to stack the bar by CompanySizeId.

I have been following this video.

import plotly.graph_objects as go
import plotly.offline as pyo
import pandas as pd

countcompany = pd.read_csv(
    'https://raw.githubusercontent.com/redbeardcr/Plotly/master/Data/countcompany.csv')

df = pd.pivot_table(countcompany, index='CompanyStatusLabel',
                    values='n', aggfunc=sum)
print(df)

data = [go.Bar(
    x=df.index,
    y=df.values,
)]

layout = go.Layout(title='Title')

fig = go.Figure(data=data, layout=layout)

pyo.plot(fig)

Code can be found here

Thanks for any help


Solution

  • If you flatten the array with the y values, i.e. if you replace y=df.values with y=df.values.flatten(), your code will work as expected.

    import plotly.graph_objects as go
    import plotly.offline as pyo
    import pandas as pd
    
    countcompany = pd.read_csv('https://raw.githubusercontent.com/redbeardcr/Plotly/master/Data/countcompany.csv')
    
    df = pd.pivot_table(countcompany, index='CompanyStatusLabel', values='n', aggfunc=sum)
    
    data = [go.Bar(
        x=df.index,
        y=df.values.flatten(),
    )]
    
    layout = go.Layout(title='Title')
    
    fig = go.Figure(data=data, layout=layout)
    
    pyo.plot(fig)