Previously, i have covered how you can plot multiple bar graph using Python’s Matplotlib library on a single axis. Here in this post we will see how we can plot multiple bar graph using Python’s Plotly library. It is an interactive visualization library which has options like saving the charts in local machine, hover, zoom, pan.
Basically bar graph or chart is used to visualize categorical data with heights or lengths proportional to the values that they represent and can be easily plotted on a vertical or horizontal axis.
Now lets plot the bar chart and see the code written in Plotly library:
- First we import the libraries used for this chart i.e Python and Plotly
import pandas as pd import plotly.graph_objects as go
- Then we read the data used for plotting the charts. you can find the data set here and print the top 5 rows.
data=pd.read_csv(r"C:\Users\Pankaj Sharma\Downloads\countries.csv") data.head()
- Now as we are trying to create chart for Top 10 countries with highest numbers in terms of population and GDP per capita for the year 2007, we have to apply all the filters as shown below.
data_2007 = data[data.year == 2007] datasort = data_2007.sort_values('population', ascending = False) datasort = datasort.head(10)
- Now lets see the Poltly code which will help us to plot the multiple bar chart.
Population = go.Bar(x = datasort["country"], y=datasort["population"],showlegend=True, name="Population") trace1 = go.Bar(x = datasort["country"], y=[0],showlegend=False,hoverinfo='none') trace2 = go.Bar(x = datasort["country"], y=[0], yaxis='y2',showlegend=False,hoverinfo='none') GDPperCapita = go.Bar(x = datasort["country"], y=datasort["gdpPerCapita"], yaxis='y2',showlegend=True, name="GDP per Capita") data = [Population,trace1,trace2,GDPperCapita] layout = go.Layout(barmode='group', legend=dict(x=0.7, y=1.2,orientation="h"), yaxis=dict(title='Population in Billions'), yaxis2=dict(title = 'GDP per Capita in Millions', overlaying = 'y', side='right')) fig = go.Figure(data=data, layout=layout) fig.show()
Here’s below the chart :
Update: Also we can plot the same bar chart using the below simple code.
fig = go.Figure( data=[ go.Bar(name='Population', x=datasort["country"], y=datasort["population"], yaxis='y', offsetgroup=1), go.Bar(name='GDP per Capita', x=datasort["country"], y=datasort["gdpPerCapita"], yaxis='y2', offsetgroup=2) ], layout={ 'yaxis': {'title': 'Population (in Billions) '}, 'yaxis2': {'title': 'GDP per Capita (in Millions)', 'overlaying': 'y', 'side': 'right'} } ) # Change the bar mode fig.update_layout(barmode='group') fig.show()
To get more detailed knowledge about charts in Plotly, you can check the official website of Plotly by Dash. Also if you want to explore more codes/posts related to Data visualization on our website, then you can find it here.
If you have any questions or if you need any help please get in touch with me using the comment section below.
Leave a Reply