The Quickest Guide to Data Visualization in Python using Matplotlib

Zahra Ahmad
Mar 2 · 4 min read
Photo by Isaac Smith on Unsplash

Data Visualization is very important in data analysis and machine learning, it allows us to have a better understanding about the pattern of some variables in our data, conclude some correlation between multiple variables, and eventually we can take the right decision based on that.

In this story, I will present how to create basic diagrams in Python. I will use the Matplotlib package, which is a 2D graphical library in Python language, it supports plotting graphics and images of the data in an attractive way.

If you want to know more about interesting packages in python, including matplotlib itself, check my previous story on medium:

Getting Started

In order to plot something, we need data, let’s start with the following data for demonstration:

Percentages in market-share

Plot a 3D Pie Chart using matplotlib

import matplotlib.pyplot as plt

labels = 'R','Python', 'SPSS', 'SAS', 'Excel'
sizes = [22, 14, 18,9,5]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue','orange']
explode = (0.1, 0, 0, 0,0)

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True)

plt.axis('equal')
plt.show()

Plot Bar Charts in Python using matplotlib

This data can also be represented using bar charts as follows:

import matplotlib.pyplot as plt

x = [-4,0,4,8,12]
heigh = [22, 14, 18,9,5]
width=3
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue','orange']
labels = 'R','Python', 'SPSS', 'SAS', 'Excel'

plt.bar(x,heigh,width,align='center',color=colors)
plt.xticks(x,labels)
plt.ylabel('The number of users')
plt.axis('equal')
plt.show()

Also, the bars can be drawn horizontally using the following code:

import matplotlib.pyplot as plt

y = [-4,0,4,8,12]
heigh = [22, 14, 18,9,5]
width=3
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue','orange']
labels = 'R','Python', 'SPSS', 'SAS', 'Excel'

plt.barh(y,heigh,width,align='center',color=colors)
plt.yticks(y,labels)
plt.xlabel('The number of users')
plt.axis('equal')
plt.show()

Line Plot in Python using matplotlib

Let us assume the number of students admitted to a college during 5 years is shown in this Table:

Total number of admitted students from 2014 to 2018

We can use the function plot to plot a line plot as follows:

import matplotlib.pyplot as plt

years=[2014,2015,2016,2017,2018]
Numbers=[702,650,585,740,810]

plt.plot(years,Numbers, linestyle='solid', color='blue')
plt.xticks(years,years)
plt.ylabel('The number of students')
plt.xlabel('Year')
plt.show()

If we do not like the line, you can apply some styling by replacing the following line:

linestyle=’solid’, color=’blue’

with multiple options for formatting and coloring as follows:

plt.plot(years,Numbers, '--b')
plt.plot(years,Numbers, '-.g')
plt.plot(years,Numbers, ':r')

Plot Data from CSV in Python using Matplotlib and Pandas

Now we will draw some advanced plots, where we will use mydata data, which can be obtained from the following link:

https://github.com/zahrasyria/data/blob/main/mydata.csv

Then you can load it to a data frame in pandas as follows:

import pandas as pd
mydata = pd.read_csv('mydata.csv',sep=',')

The data contains four variables: y, x1, x2, x3.

To facilitate accessing those features (or variables) from the data, the following code can be used:

def attach(df):
for col in df.columns:
globals()[col] = df[col]

attach(mydata)

To represent the probability distribution of the variable y we can use the function:

import seaborn as sns
import matplotlib.pyplot as plt
sns.distplot(y,kde_kws={"color": "black"},hist_kws={"color": "skyblue"})
plt.ylabel('Probability Density')

Or using different style:

sns.kdeplot(y, color="r", shade=True,legend=False)
plt.xlabel('y')
plt.ylabel('Probability Density')

Also we can use boxplot

sns.boxplot(y, orient='v',color='skyblue')

To compare more than one distribution:

sns.kdeplot(x1, label="x1")
sns.kdeplot(x2, label="x2")
sns.kdeplot(x3, label="x3")
plt.xlabel('features')
plt.ylabel('Probability Density')

Plot the Correlation Between Multiple Variables in Python Using Scatter

To plot the correlation between two variables (if it exists),

sns.scatterplot(x1,y)

Conclusion

I have presented in this article a quick overview of almost everything I have been using in matplotlib to plot awesome figures in my recent 2 years career as a Data Scientist.

Of course there are more advanced plots, but mastering what I have presented in this article will secure you a nice and representatives plots for your data exploration task.

If you liked my article, applauding it will encourage me to contribute and share more :)

And as usual, your questions and comments help me to provide better content.

MLearning.ai

Data Scientists must think like an artist when finding a solution

By MLearning.ai

A weekly collection of the best news and resources on AI & ART Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Zahra Ahmad

Written by

MSc in Data Science, I love to extract the hell out of any raw data, sexy plots and figures are my coffee

MLearning.ai

Data Scientists must think like an artist when finding a solution, when creating a piece of code.Artists enjoy working on interesting problems, even if there is no obvious answer.

Zahra Ahmad

Written by

MSc in Data Science, I love to extract the hell out of any raw data, sexy plots and figures are my coffee

MLearning.ai

Data Scientists must think like an artist when finding a solution, when creating a piece of code.Artists enjoy working on interesting problems, even if there is no obvious answer.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store