Python Data Visualization With Seaborn and Matplotlib
Data visualization is important for many analytical tasks including data summarization,
exploratory data analysis and model output analysis. One of the easiest ways to communicate
your findings with other people is through a good visualization. Fortunately, Python features
many libraries that provide useful tools for gaining insights from data.
The most well-known of these data visualization libraries in Python, Matplotlib, enables users
to generate visualizations like histograms, scatter plots, bar charts, pie charts and much more.
Seaborn is another useful visualization library that is built on top of Matplotlib. It provides data
visualizations that are typically more aesthetic and statistically sophisticated.
MATPLOTLIB VS. SEABORN
• Matplotlib is a library in Python that enables users to generate visualizations like
histograms, scatter plots, bar charts, pie charts and much more.
• Seaborn is a visualization library that is built on top of Matplotlib. It provides data
visualizations that are typically more aesthetic and statistically sophisticated.
Generating Histograms in Python With Matplotlib
Matplotlib provides many out-of-the-box tools for quick and easy data visualization. For
example, when analyzing a new data set, researchers are often interested in the distribution of
values for a set of columns. One way to do so is through a histogram.
Histograms are approximations to distributions generated through selecting values based on a
set range and putting each set of values in a bin or bucket. Visualizing the distribution as a
histogram is straightforward using Matplotlib.
For our purposes, we will be working with the FIFA19 data set, which you can download
from [Link]
To start, we need to import the Pandas library, which is a Python library used for data tasks
such as statistical analysis and data wrangling:
import pandas as pd
Next, we need to import the pyplot module from the Matplotlib library. It is custom to import
it as plt:
import [Link] as plt
Now, let’s read our data into a Pandas dataframe. We will relax the limit on display columns
and rows using the set_option() method in Pandas:
df = pd.read_csv("[Link]") //Specify the path where the dataset is stored
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
Let’s display the first five rows of data using the head() method:
print([Link]())
We can generate a histogram for any of the numerical columns by calling the hist() method on
the plt object and passing in the selected column in the data frame. Let’s do this for the Overall
column, which corresponds to overall player rating:
[Link](df['Overall'])
We can also label the x-axis, y-axis and title of the plot using the xlabel(), ylabel() and title()
methods, respectively:
[Link]('Overall')
[Link]('Frequency')
[Link]('Histogram of Overall Rating')
[Link]()
This visualization is great way of understanding how the values in your data are distributed and
easily seeing which values occur most and least often.
Generating Scatter Plots in Python With Matplotlib
Scatter plots are a useful data visualization tool that helps with identifying variable dependence.
For example, if we are interested in seeing if there is a positive relationship between wage and
overall player rating, (i.e., if a player’s wage increases, does his rating also go up?) we can
employ scatter plot visualization for insight.
Before we generate our scatter plot of wage versus overall rating, let’s convert the wage column
from a string to a floating point numerical.
For this, we will create a new column called wage_euro:
df['wage_euro'] = df['Wage'].[Link]('€')
df['wage_euro'] = df['wage_euro'].[Link]('K')
df['wage_euro'] = df['wage_euro'].astype(float)*1000.0
Now, let’s display our new column wage_euro and the overall column:
print(df[['Overall', 'wage_euro']].head())
To generate a scatter plot in Matplotlib, we simply use the scatter() method on the plt object.
Let’s also label the axes and give our plot a title:
[Link](df['Overall'], df['wage_euro'])
[Link]('Overall vs. Wage')
[Link]('Wage')
[Link]('Overall')
[Link]()
Generating Bar Charts in Python With Matplotlib
Bar charts are another useful visualization tool for analyzing categories in data. For example,
if we want to see the most common nationalities found in our FIFA19 data set, we can employ
bar charts. To visualize categorical columns, we first should count the values. We can use the
counter method from the collections modules to generate a dictionary of count values for each
category in a categorical column. Let’s do this for the nationality column:
from collections import Counter
print(Counter(df[‘Nationality’]))
We can filter this dictionary using the most_common method. Let’s look at the 10 most
common nationality values (note: you can also use the least_common method to analyze
infrequent nationality values):
print(dict(Counter(df[‘Nationality’]).most_common(10)))
Finally, to generate the bar plot of the 10 most common nationality values, we simple call the
bar method on the plt object and pass in the keys and values of our dictionary:
nationality_dict = dict(Counter(df['Nationality']).most_common(10))
[Link](nationality_dict.keys(), nationality_dict.values())
[Link]('Nationality')
[Link]('Frequency')
[Link]('Bar Plot of Ten Most Common Nationalities')
[Link](rotation=90)
[Link]()
As you can see, the values on the x-axis are overlapping, which makes them hard to see. We
can use the “xticks()” method to rotate the values:
[Link](rotation=90)
Generating Pie Charts in Python With Matplotlib
Pie charts are a useful way to visualize proportions in your data. For example, in this data set,
we can use a pie chart to visualize the proportion of players from England, Germany and Spain.
To do this, let’s create new columns that contain England, Spain, Germany and one column
labeled “other” for all other nationalities:
[Link][[Link] =='England', 'Nationality2'] = 'England'
[Link][[Link] =='Spain', 'Nationality2'] = 'Spain'
[Link][[Link] =='Germany', 'Nationality2'] = 'Germany'
[Link][~[Link](['England', 'German', 'Spain']), 'Nationality2'] = 'Other'
Next, let’s create a dictionary that contains the proportion values for each of these:
prop = dict(Counter(df['Nationality2']))
for key, values in [Link]():
prop[key] = (values)/len(df)
print(prop)
We can create a pie chart using our dictionary and the pie method in Matplotlib:
fig1, ax1 = [Link]()
[Link]([Link](), labels=[Link](), autopct='%1.1f%%',
shadow=True, startangle=90)
[Link]('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
[Link]()