Home > Software engineering >  how to plot bar chart using plotly with color parameter
how to plot bar chart using plotly with color parameter

Time:07-02

 df=pd.DataFrame({'gender':['F','F','M','M','M','M','M'],
                     'country':['USA','Belgium','USA','Russia','India','Belgium','Canada'],
                     'count':[123,421,112,445,21,442,226],
                     })

   gender  country     count
0   F       USA         123
1   F     Belgium       421
2   M       USA         112
3   M     Russia        445
4   M     India         21
5   M     Belgium       442
6   M     Canada        226

I want to plot a bar char that display the above table using Plotly package. For this i used the code below but it crash and display error:

fig = px.histogram(df,x='gender', y='count' ,color =['gender','country'],barmode = 'group')

Error:

ValueError: All arguments should have the same length. The length of argument color is 2, whereas the length of previously-processed arguments ['gender', 'count'] is 7

expected output :

enter image description here

CodePudding user response:

Try either:

fig = px.histogram(df,x='gender', y='count' ,color ='gender',barmode = 'group')

or

fig = px.histogram(df,x='gender', y='count' ,color ='country',barmode = 'group')

It would also help if you could clarify what you are trying to accomplish. Your data doesn't make much sense. I'm not exactly sure what you are trying to achieve.

EDIT: Your clarification didn't help much, but this may be what you're looking for:

fig = px.histogram(df, x='country', y='count', color = 'gender')

or based on your picture

fig = px.histogram(df, x="gender", y="count",color='country', barmode='group')

CodePudding user response:

according to the documents color parameter takes : Either a name of a column in data_frame, or a pandas Series or array_like object for that i create a Series and assigned to color

the code becomes as below:

cat = df[['gender','country']].agg(', '.join, axis=1)
fig = px.histogram(df,x=gender, y='count' ,color = cat,barmode = 'group')
                
  

      
  • Related