'how to plot a bar chart using plotly using python

i have the below dataframe

df=pd.DataFrame({'dept':['dept1','dept2','dept3','dept4','dept5'],
                 'subd':['hndf','nbf','asx','qwe','def'],
                 'jju':['0','1','1','NA','1'],
                 'rob':['1','0','NA','1','1'],
                 'ans':['0','0','1','NA','1'],
                 'zsd':['1','NA','1','1','1'],
                 'count':['4','3','3','2','4']}


        dept    subd      jju     rob  ans  zsd count
0      dept1    hndf       0      1     0      1    4
1      dept2     nbf       1      0     0      NA   3
2      dept3     asx       1      NA    1      1    3
3      dept4     qwe       NA     1    NA      1    2
4      dept5     def       1      1    1       1    4 

I need to plot a bar plot using plotly.graph_objs package

Where the

  • X axis is the df.loc[:, 'jju':'zsd']
  • Y axis is the count of '0' and '1'

expected result each item on the X axis will have 2 bars

for now i tried this code:

import pandas as pd
import plotly.graph_objs as go

res = []
for col in df.loc[:, 'jju':'zsd'].columns:
    res.append(
       go.Bar(
       x= df.index.values.tolist(),
       y = df[col].values.tolist(),
       name = col
       )
    )
layout = go.Layout(barmode = 'group')
fig = go.Figure(data = res,layout = layout)
fig.show()

But it doesn't return what i want so where i did it wrong ??



Solution 1:[1]

Is this what you need?

import plotly.express as px
fig=px.histogram(df,x=['jju','rob','ans','zsd'],barmode="group")
fig.show()

If you need to neglect the "NA" you should replace them by np.nan values :

df=df.replace('NA',np.nan)
fig=px.histogram(df,x=['jju','rob','ans','zsd'],barmode="group")
fig.show()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1