Data visualization with Python Using Seaborn and Plotly_ GDP per Capita & Life Expectency Dataset | by Fatima Zahra Iazza | Towards Data Science

This tutorial is intended to help you get up-and-running with python data visualization libraries very quickly. I choose seaborn and plotly that is the most used and awesome tools to visualize fully-interactive plots and make data looking great.
Also you will get to discover the relationship between economy and social factors. The dataset we would be dealing with in this illustration is GDP per Capita, Social support, Healthy life expectancy, Freedom to make choices, Generosity... in all over the world.
I use jupyter notebook that you can get access from Anaconda packages.
If you want to install Anaconda here.
Seaborn is a visualization library based on matplotlib, it works very well with pandas library.
One of the reasons to use seaborn is that it produces beautiful statistical plots. It is very important to realize that seaborn is a complement and not a substitute to matplotlib.
To install seaborn, you can use pip or conda at your command line or terminal with:
!pip install seabornor!conda install seaborn
Import libraries
Import libraries
Let us begin by importing few libraries, numpy (numerical python library), pandas for dataframe and dataseries, seaborn and matplotlib for visualization.
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline #use it to show plot directly below the code 
2. Read data using pandas
This data called ‘2019.csv’ in format csv file. that is the dataset that we gonna work with throughout this tutorial.
head() function return top 5 rows of dataframe as we can see below:
df= pd.read_csv('2019.csv')df.head()
1.distplot:
What i do here is simply plot a distribution of a single column in a dataframe (GDP per capita) using sns.distplot(dataofsinglecolumn).
To remove kernal density estimation plot you can use kde=False.
bins=30 represents the number of bins that define the shape of the histogram, i use 8 bins in the left plot and 30 for the other so you can see the difference.
sns.distplot(df['GDP per capita'], bins=8) out[5]sns.distplot(df['GDP per capita'], kde = False , bins = 30)out[6]
2.jointplot:
Seaborn’s jointplot displays a relationship between two variables.
Here shows plots of the two columns x and y in data using scatter plot and histogram.
sns.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df) #two ditribution
here below you can add kind of plot to draw, example kind=’reg’ means draw scatter plot with regression line, and kind=’hex’ that bins the data into hexagons with histogram in the margins.
You can see here that GDP per capita and Healthy life expectancy are positive lineary correlated. means if GDP per capita is high, Healthy life expectancy would be high too.
sns.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df,kind='reg') #plot in the right sidens.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df,kind='hex') # plot in the left
sns.pairplot(df)#relationship entire datasets
It is amazing that one simple line of code gives us this entire plot!
This represent the relationship between the entire dataset. The histogram allow us to see the distribution of a single variable while scatter plots show the relationship between two variables.
barplot is used to plot categorical variable example sex male/female...
here i use country as category and plot GDP per capita of top 3 countries using head() function.
sns.barplot(x=df['Country or region'].head(3),y=df['GDP per capita'],data=df)
What i do here is select 4 columns of the data and use corr() function to find correlation between the data that have been selected.
# Matrix form for correlation datadata_select = df[['GDP per capita','Social support','Healthy life expectancy','Perceptions of corruption']]data_select.corr()
you can see here a matrix form that indicates some sort of values which represent the level of correlation, that level range in general from -1 to 1.
if corr value approches to 1, that means variables have strong positive correlation.
sns.heatmap(df_select.corr(), cmap='coolwarm')
here what heatmap really does is represent the data correlation values as colors in the gragh based on some sort of gradient scale:
you can change color map by adding cmap= ‘...’ , example ‘Greens’ , ‘Blues’, ‘coolwarm’...For all the colormaps, check out: http://matplotlib.org/users/colormaps.html
Plotly is a data visualization library that you can use to create different types of interactive charts, maps and plots..
here plotly website
The first thing you can do is to install plotly and cufflinks libraries.
cufflinks connects plotly with pandas, you can’t make plot from dataframe unless cufflinks installed.
!pip install plotly!pip install cufflinks
To connect with chart_studio, you can go to home page plotly to sign up and get your api_key in settings account.
Since plotly is an online platform, login credential must be introduced in order to use it in online mode.
chart_studio.tools.set_credentials_file(username='XXXX, api_key='xxxxxxxxxx')
Below import plotly and cufflinks on jupyter notebook, also chart_studio, plotly tools and graph object.
cf.go_offline()cf.set_config_file(offline =False , world_readable= True)
In this article we will use online mode which is quite enough for Jupyter Notebook usage.
First i select two columns in dataset; Healthy life expectancy and GDP per capita, then i create a dictionary for title name and xaxis / yaxis names and put them in layout object.
I use dict() function for example; dict(a=8, b=10) instead of {“a”: 8, “b”: 10 }
To plot the dataframe as a line chart all you have to do is call iplot method of the dataframe object.
cufflinks and plotly allow to plot data using the syntax data.iplot, then pass in a filename and layout created.
data= df[['Healthy life expectancy', 'GDP per capita']]layout = dict(title = 'Line Chart From Pandas DataFrame', xaxis= dict(title='x-axis'), yaxis= dict(title='y-axis'))data.iplot(filename='cf-simple-line-chart', layout=layout)
the mode parameter should always be set to “markers” , by default plotly will draw lines between data points. So if you want the points with no lines, you need to make sure to set plot mode as a markers.
Just like the previous example, we need a fig object, it should be a dictionary object that contain two dictionaries one for data and one for layout.
In the data dictionary we define two sets of x and y variables to be plotted, in both plots the x variable will be the same, this allows to compare GDP per capita and Healthy life expectancy relate with countries column.
Then i create data object that contains both data1 and data2 using data.go syntax, and assign to mydata variable.
Also create the layout object and pass in the title of scatter plot.
data1=go.Scatter(x=df['Country or region'],y=df['GDP per capita'], name="GDP per capita", mode="markers") data2=go.Scatter(x=df['Country or region'],y=df['Healthy life expectancy'],name="Healthy life expectancy",mode="markers")mydata = go.Data([data1, data2])mylayout = go.Layout( title="GDP per capita vs. Life expectancy")fig = go.Figure(data=mydata, layout=mylayout)chart_studio.plotly.iplot(fig)
There we go our plot using chart_studio package!
Here the same code but i use mode=”lines + markers” , it will be connect data points as lines and at the same time shows the scatter plot.
Here shows how to customize colors in plotly.
Here we need to use a dictionary object called color_theme and we gonna generate a list color that contains the RGBA codes for the colors we want to use in our bar chart.
color_theme = dict(color=['rgba(169,169,169,1)', 'rgba(255,160,122,1)','rgba(176,224,230,1)', 'rgba(255,228,196,1)',                          'rgba(189,183,107,1)', 'rgba(188,143,143,1)','rgba(221,160,221,1)'])
Now i will show you how to create Bar charts using plotly .
Here we use trace object to specify what kind of chart we want. So in this case we use go.Bar() function then we pass in two variables x and y that represent respectively the 7 countries on the head of data and Healthy life expectancy, also pass in the color_theme that we’ve already defined.
Now let’s specify our layout parameters, in this code i use just one parameter to name the title of our plot you can add x-axis and y-axis names.
Finally plot this using iplot() function and then pass in our data.
trace0 = go.Bar(x=df['Country or region'].head(7), y=df['Healthy life expectancy'], marker=color_theme)data = [trace0]layout = go.Layout(title='Healthy life expectancy')fig = go.Figure(data=data, layout=layout)chart_studio.plotly.iplot(fig, filename='color-bar-chart')
Box plot usued usually in statistics, it gives us more information on how data spread out by measure median, mean and mode of the dataset.
In the code below we just select 2 columns of our data, then we use iplot method and pass in an argument to specify the kind of plot, then we give file name of our boxplot.
df_select = df[['GDP per capita','Healthy life expectancy']] df_select.iplot(kind='box', filename='box-plot')
Here i create a simple pie chart using the index of 10 countries as labels, and plot the GDP per capita values for each country.
Then create a gragh object using go.Pie() and fill in labels and values variables. finally plot this using iplot()function.
labels = df['Country or region'].head(10).value_counts().indexvalues = df['GDP per capita'].head(10).valuestrace = go.Pie(labels=labels, values=values)chart_studio.plotly.iplot([trace], filename='basic_pie_chart')
Using plotly is the simplest way to generate maps in python.
We have two main types of plotly mapping objects; data object and layout object.
First we need data to pass in a dictionary and set parameters for the data in our map. Let’s start by passing choropleth type, this means what type of map we want plotly to generate. Then define our colorscale and reverse the scale to have yellow down and violet up the scale. We set locations as countries in the dataframe, and z variable that is represented by the colors in the map. Lastly we gonna pass in the text argument to define the text that is displayed when you move over the map.
Second create a layout dictionary to set title of our map. Then create a new dictionary that contains data and layout objects we call it fig.
To plot this we just gonna call iplot method on our fig object and then give in a file name. Here we go...
data = dict(        type = 'choropleth',        colorscale = 'Viridis',        reversescale = True,        locations = df['Country or region'],        locationmode = "country names",        z = df['GDP per capita'],        text = df['Country or region'],        colorbar = {'title' : 'GDP per capita_world'},      )    layout=dict(title_text = '2019 GDP per capita by State')fig = go.Figure(data=data,layout=layout) chart_studio.plotly.iplot(fig, filename='choropleth')
Data visualization is a great tool to get data more readable and make a huge chance for you to discover more insights in the real world.
All of the code for this article is available on GitHub . The charts are all interactive and can be viewed on plotly here.
I welcome feedback . I can be reached on Linkedin here.