Matplotlib -Data Visualization
By: Upendra Vijay
Tags: Data Visualization, Graph, Data Science, Matplotlib, Python

Getting Started

We will begin by importing Matplotlib using:

import matplotlib.pyplot as plt

If you’re using the Jupyter notebook we can easily display plots as static images next to the code cell using: %matplotlib inline.

We are now ready to begin creating our plots. Let’s create a blank Figure using the .figure() method. this will give us the canvas to draw the axes.

fig= plt.figure()

Now we need to add axes to it using the .add_axes() method. The add_axes() method takes in a list of four arguments [x0, y0, width, height] where (x0,y0) define the coordinate of the lower-left(0,0) point of the axes in the canvas. So the axes is positioned on absolute coordinates in the canvas.

axes= fig.add_axes([0.0,0.0,0.8,0.8])

# here width and height are the 80 percentage of canvas.

Now let’s plot our x and y arrays on axes:

fig= plt.figure()

axes= fig.add_axes() x=[1,2,3,4,5,6,7]

y=[1,4,9,16,25,36,49]

axes.plot(x,y)

SubPlots:

plt.subplots

we noted that the .figure() method will give us the canvas to draw the axes. this canvas can contain multiple graphs. Let’s try to put in two sets of the graph on one canvas:

fig= plt.figure()

axes1= fig.add_axes([0.0,0.0,0.4,0.4])

axes2= fig.add_axes([0.5,0.0,.4,0.4]) x=[1,2,3,4,5,6,7]

y=[1,4,9,16,25,36,49]

axes1.plot(x,y)

axes2.plot(x,y)

We can also create multiple plots in the object-oriented approach using the .subplots() method. The .subplots() method takes in nrows, which is the number of rows the canvas should have, and ncols, the number of columns the canvas should have.

For example, we can create a 2 by 2 subplots like this:

canvas,axis=plt.subplots(2,2)

axis[1,1].plot(x,y)

axes sharing

fig=plt.figure()

ax1 = plt.subplot(211)

ax2 = plt.subplot(212, sharex = ax1)

Matplotlib allows us to create customized plots by specifying the figure size, and DPI by simply specifying the figsize and dpi arguments. The figsize is a tuple of the width and height of the figure (in inches), and dpi is the dots-per-inch (pixel-per-inch).

Now, let’s go ahead and specify that we want a figure having width=8 , height=2 , and dpi=100 .

fig= plt.figure(figsize=(4,4),dpi=100)

axes= fig.add_axes([0.0,0.0,0.8,0.8])

x=[1,2,3,4,5,6,7]

y=[1,4,9,16,25,36,49]

axes.plot(x,y)

We can do the same thing with subplots() like this:

canvas,axis=plt.subplots(2,2,figsize=(4,4),dpi=100)

axis[1,1].plot(x,y)

Legends:

Legends allow us to distinguish between plots. With Legends, you can differentiate one plot from another. we need to add a legend using .legend() and then specify the label=” ” attribute for each plot like below:

fig= plt.figure(figsize=(4,4),dpi=100)

axes= fig.add_axes([0.0,0.0,0.8,0.8]) x=[1,2,3,4,5]

square=[1,4,9,16,25]

cube=[1,8,27,64,125]

axes.plot(x,square, label=’square’)

axes.plot(x,cube,label=’cube’) axes.legend()

Plot range:

Matplotlib allows us to set limits for our plots. We can easily configure the range of our plots using the set_ylim and set_xlim methods of the axis object. For example, we can choose to show only plots between 0 to 1 of the x axis , and 0 to 5 of the y axis :

fig= plt.figure(figsize=(4,4),dpi=100)

axes= fig.add_axes([0.0,0.0,0.8,0.8])

x=[1,2,3,4,5]

square=[1,4,9,16,25]

cube=[1,8,27,64,125]

axes.plot(x,square, label='square')

axes.plot(x,cube,label='cube')

axes.legend()

axes.set_ylim([0,150])

axes.set_xlim([0,5])

X and Y labels and Title:

We can add x and y labels and title to our plot using set_xlabel, set_ylabel, set_title

fig= plt.figure()

axes= fig.add_axes([0.0,0.0,0.8,0.8]) x=[1,2,3,4,5,6,7]

y=[1,4,9,16,25,36,49]

axes.plot(x,y) axes.set_title('Getting Started With Graph')

axes.set_xlabel('-----------------x direction--------------->')

axes.set_ylabel('-----------------y direction--------------->')

Plot Appearance

Matplotlib gives us a lot of options for customizing the appearance of our plots. By changing line color using color=’red’ . by changing the opacity of the graph using alpha=0.5. This value ranges from zero to one with zero being fully transparent and one being entirely opaque. Reducing alpha will make your plot objects see-through, allowing multiple layers to be seen at once as well as allowing overlapping points to be distinguished.

we can also apply the style sheet to the graph as follows

from matplotlib import style

print(plt.style.available)# ['ggplot','bmh','dark_background',....]

style.use('bmh') import numpy as np

label = ['Adventure', 'Action', 'Drama', 'Comedy','Horror']

no_movies = [941,854,4595,942,509]

plt.bar([x for x in range(0,len(label))], no_movies)

plt.xticks([0,1,2,3,4], label, rotation=30)

Special Plot Types

Scatterplot: A scatter plot is a type of plot that shows the data as a collection of points. Scatter Plots are usually used to represent the correlation between variables. It also helps it identify outliers.

import numpy as np

import matplotlib.pyplot as plt x=[x for x in range(1,50)]

y=[x**2 for x in range(1,50)] plt.scatter(x, y)

Bar chart: A bar chart is a chart that presents categorical data with rectangular bars with height proportional to the values that they represent. So in short, bar graphs are good if you to want to present the data of different groups that are being compared with each other.

import matplotlib.pyplot as plt

import numpy as np

label = ['Adventure', 'Action', 'Drama', 'Comedy','Horror']

no_movies = [941,854,4595,942,509]

plt.bar([x for x in range(0,len(label))], no_movies)

plt.xticks([0,1,2,3,4], label, rotation=30)

Histogram: A histogram takes in a series of numerical data and divides the data into a number of bins. It then plots the frequency data points in each bin. It is useful to display the count of data in ranges.

Examples of this might be age groups, or scores on a test. Rather than showing every single age a group might be, maybe you just show people from 20–25, 25–30… and so on. Here’s an example:

import numpy as np

fig= plt.figure(figsize=(4,4),dpi=100)

axes= fig.add_axes([0.0,0.0,0.8,0.8])

x = np.random.normal(size = 1000) axes.hist(x,bins=20,label=’square’)

ikds