This post extends the post on bar graph in matplotlib and seaborn. Bar graph/chart is a common type of visualization used to present categorical data using rectangular bars. Bar charts come in different types such as vertical, horizontal, stacked (either vertical or horizontal), grouped and 100% stacked bar charts. It is used to compare the relative sizes between two or more categories of data. In this post we will look at how to create bar graphs in plotly.

plotly-logo

When to Use Bar Graph

  1. Compare between two or more different groups in data.
  2. Track change over time. Note: Suitable when the changes are too large otherwise use line graph.

How to Use Bar Graph

  1. Bars should be of same type. Avoid mixing 3D and 2-D bars.
  2. The scale of values should always start from zero unless otherwise.
  3. Select the colours to use carefully.
  4. Order the bars with some criteria that best presents the insights.
  5. To maximise the visibility and appearance of all components use different variations of bar charts (vertical, horizontal, grouped etc.).
  6. Include values in the bars for users to make actual comparison between groups.

Bar Graph in Plotly

Load Required Libraries

                    

import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

Load Data

                    

score_df = pd.DataFrame(
    {
        "Student": ["Tom", "Peter","Simon", "Mary", "Jane","King","Hillary","Ethan","Page"],
        "Math": [79.00, 67.00,80.00, 84.00, 70.00,60.00,90.00,76.00,75],
        "Physics":[63.00, 98, 60.00, 90,84.00, 77.00,55.00,70,66.00],
        "Computer":[84.00,78.00, 57.00, 88.00, 75.00,93.00,92.00,98.00,90.00],
    }
)

score_df['Total']=score_df[['Math','Physics','Computer']].apply(np.sum,axis=1)
score_df

matplotlib-share-visualization-dataframe

Simple Bar Graph

                    

fig = px.bar(score_df, x='Student', y='Total',text='Total',color='Student')
fig.update_traces(texttemplate='%{text:.2f}', textposition='inside')

fig.update_layout(title={'text': 'Students Score','y':0.95,'x':0.5, 'xanchor': 'center','yanchor': 'top'},
                  autosize=True,margin=dict(t=70,b=0,l=0,r=0), xaxis_title='Year', yaxis_title='Rate',
                  font=dict(size=20, family='Times New Romans', color='brown') )

fig.update_xaxes(showline=True, linewidth=1, linecolor='white', gridwidth=3, gridcolor='white', mirror=True)
fig.update_yaxes(showline=True, linewidth=1, linecolor='white', gridwidth=3, gridcolor='white', mirror=True)

fig.show()

plotly-simple-bar-graph-in-plotly-express

Stacked Bar Graph

                    

score_melt_df=pd.melt(score_df.reset_index(),id_vars=[‘Student’],value_vars=[‘Math’,’Physics’,’Computer’],
value_name=’Score’)
score_melt_df[‘Course’]=score_melt_df[‘variable’]

fig = px.bar(score_melt_df, x='Student' , y='Score', text='Score',color='Course')
fig.update_traces(texttemplate='%{text:.2s}', textposition='inside')

fig.update_layout(title={'text': 'Students Score','y':0.95,'x':0.5, 'xanchor': 'center','yanchor': 'top'},
                          legend=dict(yanchor="top",y=0.98,xanchor="right",x=0.95),
                  autosize=True,margin=dict(t=70,b=0,l=0,r=0), xaxis_title='Year', yaxis_title='Rate',
                  font=dict(size=20, family='Times New Romans', color='brown') )

fig.update_xaxes(showline=True, linewidth=1, linecolor='white', gridwidth=3, gridcolor='white', mirror=True)
fig.update_yaxes(showline=True, linewidth=1, linecolor='white', gridwidth=3, gridcolor='white', mirror=True)

fig.show()

plotly-stacked-bar-graph

Grouped Bar Graph

                    

fig=go.Figure()
fig.add_trace(go.Bar(x=score_melt_df['Student'], y=score_melt_df[score_melt_df['Course']=='Math']['Score'], 
                     name='Math',marker_color='Teal'))
fig.add_trace(go.Bar(x=score_melt_df['Student'], y=score_melt_df[score_melt_df['Course']=='Physics']['Score'], 
                     name='Physics',marker_color='skyblue'))
fig.add_trace(go.Bar(x=score_melt_df['Student'], y=score_melt_df[score_melt_df['Course']=='Computer']['Score'], 
                     name='Computer',marker_color='orange'))

fig.update_layout(title={'text': 'Students Score','y':0.95,'x':0.5, 'xanchor': 'center','yanchor': 'top'},
                          legend=dict(yanchor="top",y=0.98,xanchor="right",x=0.95),
                  autosize=True,margin=dict(t=70,b=0,l=0,r=0), xaxis_title='Year', yaxis_title='Rate',
                  font=dict(size=20, family='Times New Romans', color='brown') )

fig.update_xaxes(showline=True, linewidth=1, linecolor='white', gridwidth=3, gridcolor='white', mirror=True)
fig.update_yaxes(showline=True, linewidth=1, linecolor='white', gridwidth=3, gridcolor='white', mirror=True)

fig.show()

plotly-grouped-bar-graph

For complete code check the jupyter notebook here.

Conclusion

Bar charts are important type of visualizations for presenting data with discrete groups. They are used to compare relative relationship between categories with bars. They are also useful in showing trend between large time intervals. In this post we have looked at what’s bar chart, when to use them and how to use them with plotly. In the next post we will look at interactive Pie Charts and how to use them in plotly. To learn about line graph in plotly check our previous post here. You can also learn about bar chart in seaborn in our other post here.

Bar Graphs in Plotly

Post navigation


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x