Data Visualization with Matplotlib in Python | by Anh T. Dang | Towards Data Science

Before you analyze data, one of the first things you have to perform is data visualization. In Python, there are a number of high-quality visualization libraries. The most popular general-purpose visualization library is Matplotlib1, which mainly focuses on generating static publication-quality 2D and 3D graphs. We can use it for many different plots such as histograms, bar plots, heat maps, line plots, scatter plots, and many others.
There are some of the important concepts that you shall come across and use in Matplotlib, and their meanings or roles.
Axis — this represents a number line, and is used to determine the graph limits.
Axes —these represent what we construe as plots. A single figure can hold as many axes as possible.
Artist — refers to everything that you can see on your figure, for example collection objects, Line2D objects and Text objects. Keep in mind that most of the artists are on the axes.
Figure — refers to the entire figure you are working on.
A Figure can contain multiple Axes instances, for example, to show multiple panels in a figure or to show insets within another Axes instance.
The Matplotlib library might seem rather complex at first, but with basic coding knowledge, it should be easier for you. The following is a list of the plots you will use in Matplotlib.
Quiver — used to create 2D arrow fields
Step — used to create a step plot
Stem — used to build a stem plot
Scatter — creates a scatter plot of x against y
Stackplot — used to create a plot for a stacked area
Plot — creates markers or plot lines to your axes
Polar — creates a polar plot
Pie — creates a pie chart
Barh — creates a horizontal bar plot
Bar — creates a bar plot
Boxplot — creates a whisker and box plot
Hist — used to create a histogram
Hist2d — used to create a histogram plot in 2D
In addition, if you frequently work with images, you should use the following image functions.
Imshow — used to show images on your axes
Imsave — used to save arrays in the form of an image file
Imread — used to read files from images into arrays
All the scripts in this book have been executed via the Jupyter notebook. Therefore, you should have the Jupyter notebook installed or create an account on Saturn Cloud.
import matplotlib as mpl 
import matplotlib.pyplot as plt

plt.style.use('default')

import numpy as np

%matplotlib inline

import math

x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.grid(True, which='both')
plt.plot(x,y)

[<matplotlib.lines.Line2D at 0x7fa6a4636490>]
x = np.linspace(0, 20)

plt.plot(x,  .5 + x)
plt.plot(x, 1 + 2 * x, '--')

[<matplotlib.lines.Line2D at 0x7fa6a45b7810>]
plt.plot(x,  .5 + x, color='blue')              # specify color by name
plt.plot(x, 1 + 2 * x, '--', color='#FFDD44')   # Hex code (RRGGBB from 00 to FF)
plt.plot(x, np.cos(x), (1.0,0.2,0.3))           # RGB tuple, values 0 and 1

[<matplotlib.lines.Line2D at 0x7fa6a44f2b50>,
 <matplotlib.lines.Line2D at 0x7fa6a447d250>]
x = np.linspace(0, 10, 1000)

plt.plot(x, np.sin(x), linestyle='solid') 
plt.plot(x, np.cos(x), linestyle='dotted')

[<matplotlib.lines.Line2D at 0x7fa6a443d390>]
plt.plot(x, np.tan(x))
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5);

plt.plot(x, np.sin(x)) 

plt.xlim(10, 0)
plt.ylim(1.0, -1.0);

plt.plot(x, np.sin(x)) 
plt.axis([0, 10, -1.0, 1.0]);

plt.title("titlte")
plt.xlabel("x-axis") 
plt.ylabel("y-axis")

Text(0, 0.5, 'y-axis')
plt.plot(x, np.sin(x), '-g', label='sin(x)') 
plt.plot(x, np.cos(x), ':b', label='cos(x)') 
plt.legend()

<matplotlib.legend.Legend at 0x7fa6a42b44d0>
from sklearn.datasets import load_iris 
iris = load_iris()
features = iris.data.T
plt.scatter(features[0], features[1], alpha=0.2, s=100*features[3], c=iris.target, cmap='viridis')
plt.xlabel(iris.feature_names[0]) 
plt.ylabel(iris.feature_names[1])

Text(0, 0.5, 'sepal width (cm)')
fig = plt.figure()

x = np.linspace(0, 10, 50)
dy = 0.8
y = 2.5 * np.sin(x / 20 * np.pi) + np.random.randn(50)

plt.errorbar(x, y, yerr=dy, fmt='.k')

<ErrorbarContainer object of 3 artists>
plt.errorbar(x, y, yerr=dy, fmt='o', color='black', ecolor='lightgray', elinewidth=3, capsize=0)
fig = plt.figure()

<Figure size 432x288 with 0 Axes>
x = [20, 200, 2000, 20000, 200000]
y = [30, 300, 3000, 30000, 300000]

plt.loglog(x, y)
fig = plt.figure(figsize=(4, 3), dpi=70)

<Figure size 280x210 with 0 Axes>
t = np.arange(0,5,0.1)

y1 = np.sin(2*np.pi*t)
y2 = np.sin(2*np.pi*t)

plt.subplot(211)
plt.plot(t,y1,'b-.')
plt.subplot(212)
plt.plot(t,y2,'r--')

plt.show()

t = np.arange(0.,1.,0.05)

y1 = np.sin(2*np.pi*t)
y2 = np.cos(2*np.pi*t)

plt.subplot(121)
plt.plot(t,y1,'b-.')
plt.subplot(122)
plt.plot(t,y2,'r--')

plt.show()

import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')

x = ['Viettel', 'VNPT', 'Mobiphone']
revenue = (37600000, 6445000, 6045000)


x_pos = [i for i, _ in enumerate(x)]

plt.bar(x_pos, revenue, color='green')
plt.xlabel("Telco")
plt.ylabel("VND")
plt.title("Telecom service revenues in Vietnam")

plt.xticks(x_pos, x)

plt.show()

N = 3

revenue = (37600000, 6445000, 6045000)
tax = (37000000, 4476000, 5403000)

ind = np.arange(N) 
width = 0.35       
plt.bar(ind, revenue, width, label='Revenue')
plt.bar(ind + width, tax, width,
    label='Tax')

plt.ylabel('VND')
plt.title('Telecom service revenues in Vietnam')

plt.xticks(ind + width / 2, ('Viettel', 'VNPT', 'Mobiphone'))
plt.legend(loc='best')
plt.show()

telcos = ['Viettel', 'VNPT', 'Mobiphone']

revenue = (37600000, 6445000, 6045000)
tax = (37000000, 4476000, 5403000)

ind = [x for x, _ in enumerate(telcos)]

plt.bar(ind, revenue, width=0.8, label='revenue', color='gold', bottom=tax)
plt.bar(ind, tax, width=0.8, label='tax', color='silver')

plt.xticks(ind, telcos)
plt.ylabel("VND")
plt.xlabel("Telco")
plt.legend(loc="upper right")
plt.title("Telecom service revenues in Vietnam")

plt.show()

import numpy as np
import matplotlib.pyplot as plt

X = np.random.randn(1000)
plt.hist(X, bins = 20)
plt.show()

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randn(100)

plt.boxplot(data)
plt.show()

import matplotlib.pyplot as plt

telcos = 'Viettel', 'VNPT', 'Mobiphone', 'Vietnammobile', 'Gtel'
data = [46.7, 22.2, 26.1, 2.9, 2.1]

fig1, ax1 = plt.subplots()
ax1.pie(data, labels=telcos, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')

plt.show()

fig1.savefig('my_figure.png')

fig1.savefig('my_figure.png', transparent=True)

 

Let’s see how to use it. We must first import the pyplot module from our Matplotlib package before we can create a plot.
We will use the plt.style directive to choose appropriate aesthetic styles for our figures. Here we will set the default style, which ensures that the plots we create use the default Matplotlib style.
Simplify, execute the following command.
You also can use different styles. Read further here3. Note that the stylesheets used here are supported as of Matplotlib version 1.5, so if you are using an earlier version of Matplotlib, only the default style is available.
We will learn how to plot a sine wave in Python w/ Matplotlib. We will be plotting sin(x) along with its multiple and sub-multiple angles between the interval 0 and 2π.
The NumPy library has the sin() function, which takes an array of values and provides the sine value for them.
To lead to static images of your plot embedded in the notebook use the following command.
The math library will help in defining pi to generate random values of the x-axis.
Computing the value of the sin wave at the for each sample, and then proceed to specify the x and y axis labels, and the plot title as shown.
The second plot that we are going to plot is a line plot. A line plot is the simplest of all the Matplotlib plots. A line plot is basically used to plot the relationship between two numerical sets of values.
Now, we create two unique lines with different styles. Determining the x coordinates using linspace () function. The x coordinates start at 0 and end at 20, hence you should have the following function.
Plot the lines on your axis in the following order.
In the above example, the first one, which will act as the default line, is the solid line style, while the second one will have a dashed line.
To adjust the color, you can use the color keyword, which accepts a string argument representing virtually any imaginable color. The color can be specified in a variety of ways.
If no color is specified, Matplotlib will automatically cycle through a set of default colors for multiple lines.
Also, we can adjust the line style using the linestyle keyword as follows.
The most basic method to adjust axis limits is to use the plt.xlim() and plt.ylim() methods.
If you want either axis to be displayed in reverse, simply execute this command.
In addition, we also can set the x and y limits with a single call by passing a list that specifies [x-min, x-max, y-min, y-max].
We can create the labeling of plots such as titles, axis labels, and simple legends.
Titles and axis labels are the simplest such labels as follows.
Creating a legend can be done via the plt.legend() method.
A logarithmic plot is essentially a basic plot, but it is set on a logarithmic scale. The difference between this and a normal linear scale is that the intervals are set in order of their magnitude. We have two different types of log plots.
The log-log plot.
The semi-log plot.
For example, execute the below code snip to show a logarithmic plot.
A scatter plot is used to plot the relationship between two numeric columns in the form of scattered points. Normally, a scatter plot is used when for each value in the x-axis, there are multiple values in the y-axis.
Using the plt.scatter() function to create scatter plots as follows. For example, we use the Iris data from the sklearn library, where each sample is one of three types of flowers that have had the size of its petals and sepals carefully measured.
We can explore simultaneously four different dimensions of the data: the (x, y) location of each point corresponds to the sepal length and width, the size of the point is related to the petal width, and the color is related to the particular species of flower.
Error bars are useful to problem solvers because error bars show the confidence or precision in a set of measurements or calculated values. A basic errorbar can be created with the plt.errorbar() method.
We make the error-bars lighter than the points themselves as follows.
To create multiple subplots, we can also use the subplot() function to create multiple drawing areas in the main figure.
Also, we can create vertical divisions from the plots above using the code below.
Bar charts are used to display values associated with categorical data. The plt.bar() function, however, takes a list of positions and values, the labels for x are then provided by plt.xticks().
For example, we show the 2019 service revenue of telcos in Vietnam as follows.
We can also include multiple X values on the same chart. Viettel is the biggest taxpayer in Vietnam in 2019 as follows.
With stacked bar charts we need to provide the parameter bottom, this informs matplotlib where the bar should start from, so we will add up the values below.
Histograms are graphical representations of a probability distribution. In fact, a histogram is just a specific kind of a bar chart.
The following script draws 1000 values from a normal distribution and then generates histograms with 20 bins.
Boxplot allows you to compare distributions of values by conveniently showing the median, quartiles, maximum, and minimum of a set of values. The following script shows a boxplot for 100 random values drawn from a normal distribution.
To compare the relative importance of quantities, nothing like a pie chart.
To save a figure to a file, we can use the savefig method . This method takes a string with the output filename as first argument, as well as several optional keyword arguments. For example, to save the previous figure as a PNG file, you can run this.
The figure canvas can also be made transparent using the transparent=True argument to savefig.
Output.
It’s all about data visualization with Matplotlib in Python.