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 ??

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x