0% found this document useful (0 votes)
10 views14 pages

RM-Subplots, Scatter Plots and Reading Image – Tutorial

This document is a tutorial on creating various plots using Matplotlib, including line charts, scatter plots, and subplots. It explains how to customize these plots and introduces the FacetGrid function from the Seaborn library for creating multiple plots efficiently. Additionally, it covers how to read and display images using Matplotlib's pyplot module.

Uploaded by

thanvarshini01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views14 pages

RM-Subplots, Scatter Plots and Reading Image – Tutorial

This document is a tutorial on creating various plots using Matplotlib, including line charts, scatter plots, and subplots. It explains how to customize these plots and introduces the FacetGrid function from the Seaborn library for creating multiple plots efficiently. Additionally, it covers how to read and display images using Matplotlib's pyplot module.

Uploaded by

thanvarshini01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

MDS5103/MSBA5104 Segment 05

SUBPLOTS, SCATTER
PLOTS, AND READING
IMAGES - TUTORIAL
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

Table of Contents

1. Line Chart 4
2. Scatter Plot 6
3. Subplots 7
3.1 Subplot with Primary and Secondary Axes 8
3.2 Subplot() Function 10
4. FacetGrid 12
5. Reading Images 13

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 2/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

Introduction

To create rich plots, it is sometimes necessary to include more than one plot into a single
figure. This can be achieved using the concept of ‘Subplots’ or ‘Facetgrids’. This topic
provides a detailed explanation on these concepts. This topic also demonstrates the
working of a few other plots like ‘Line plot’, ‘Scatter Plot’ and so on with real-life data.

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 3/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

1. Line Chart
In Pyplot of Matplotlib, the default functionality of the ‘plot()’ function is to create a line plot.
To illustrate this, we use the marketing data available in ‘MMix.csv’.

data=pd.read_csv("MMix.csv")
data.head()

Output

Base
NewVolSales Price Radio TV InStore
19564 15.02928 245 145.4 15.452 …
19387 15.02928 314 66 16.388 …

There are 104 weeks of data for ‘Sales Volume’. The code below displays them as a line plot.

plt.plot(data2['NewVolSales'])
plt.xlabel("Week")
plt.ylabel("Volume Sales in thousands")
plt.title("Volume Sales")

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 4/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

Output
Text(0.5, 1.0, 'Volume Sales')

The output above displays the sales volume as a line chart.


The line chart can be customised to change the colour, the style of the line, the shape and
size of the marker and so on. The code below demonstrates the same.

plt.plot(data2['NewVolSales'], c = 'M', ls = "--", marker = "s", ms = 6)


plt.xticks(rotation = 'vertical')
plt.xlabel('Volume Sales in 1000 units')
plt.show()

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 5/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

Output

The parameter ‘color’ with the value ‘M’ will result in the line being plotted in the colour
‘magenta’.

2. Scatter Plot
Scatter plot is a ‘Bivariate plot’. This is mostly used to study the correlation or relationship
between two continuous variables. The ‘scatter()’ function from the pyplot module can be
used to create scatter plots.
Syntax
scatter(x_axis_data, y_axis_data, [other customization parameters] )

The code below demonstrates the creation of the scatter plot. This creates the scatter plot
for age and income. The values of age (data[‘Age’] ) are provided along the x-axis and the
values of income ( data[‘Income’]) are provided along the y-axis. The customisation
parameters like ‘color’, ‘alpha’ can be provided to enhance the appearance of the plot.

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 6/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

plt.scatter(x=data['Age'],y = data['Income'], color = "magenta", alpha = 0.5)


plt.title('Relationship Between Age and Income')
plt.xlabel('Age')
plt.ylabel('Income')

Output

The output above indicates that there is a positive correlation between the age and the
income.

3. Subplots
If one wants customised plots or multiple plots of different types in the same plot area, it is
important to understand the working of the ‘subplots()’ functions within the matplotlib
library. The subplot() function returns two objects as shown in the code below– a figure
object and an axes (or subplot) object.

print( type(plt.subplots()[0]))
print( type(plt.subplots()[1]))

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 7/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

Output
<class 'matplotlib.figure.Figure'>
<class 'matplotlib.axes._subplots.AxesSubplot'>

‘Figure’ is the entire plot area. ‘Axes’ is an object within the subplot. Note that it is different
from the x and y axes. Axes contain figure elements including ‘x-label’, ‘y-label’, ‘title’, type of
the plot to be rendered, ticks and so on . Figure 1 shows the relationship between various
elements. For every plot, there is one Figure object. A ‘Figure’ object can have one or more
subplot or axes object. Each axes object can be activated to plot on the same.

Figure

Sub plot

Axes can be activated to render various plots

Figure1: Elements of Plot

3.1 Subplot with Primary and Secondary Axes


The code below demonstrates the creation of a plot within the primary and secondary axes
assuming there is only one subplot. The ‘subplot()’ method returns the figure and the axes
object. The axes object is not the same as the plot object and it has its own methods.
Therefore, we use the ‘set_xlabel()’ to create the labels along the x-axis. The function
‘axes.plot()’ will activate the specified axes object. To create a secondary y-axes, the ‘twinx()’
method can be invoked. The details for the y-axis can then be set on the newly created axes
object. The code plots the ‘Volume Sales’ on the primary y axes and the ‘Radio TRPs’ in the
secondary y axes.

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 8/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

fig, ax1 = plt.subplots()


ax1.plot(data2['NewVolSales'])
ax1.set_xlabel('time (w)')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('Volume Sales')
ax2 = ax1.twinx()
ax2.plot(data2['Radio '], 'r')
ax2.set_ylabel('Radio')
fig.tight_layout()
plt.show()

Output

The output is generated as shown above. These types of graphs can answer questions like
- ‘For an increase in ‘Radio TRP’ – Is there a corresponding peak in the volume sales ‘?

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 9/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

3.2 Subplot() Function


The ‘subplot()’ function can be used to render two different types of plots in the same plot
area. This can also be referred to as two or more different axes in the same figure object.
Each axes needs to be activated before a graph is plotted on it. This is done using the
‘subplot()’ function.
Syntax
subplot(nrows, ncolumns, index)

The ‘subplot()’ function takes the number of rows and columns as parameters. This creates
( rows X column ) subplots. The index identifies the subplot that needs to be activated. For
example, subplot (233) or subplot(2,3,3) creates six (2x3) axes and activates the axes at the
top right corner as shown in Figure 2.

Figure 2: Top Right Axes referring to subplot(2,3,3)

The code below demonstrates the creation of scatter plot and a box plot within the same
figure. The ‘subplot(1,2,1)’ function creates two subplots with 1 row and 2 columns. Since
the third parameter is 1, the first axes are activated. A scatterplot created using the
‘scatter()’ function is now rendered in this axes. To create a boxplot within the same figure,

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 10/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

the next axes must be activated. This is done by using ‘subplot(1,2,2)’. Once activated, the
‘boxplot()’ function can be used to render the plot.
# Create a figure with 1x2 subplot and make the left subplot active
plt.subplot(1, 2, 1)
# Plot in blue the % of degrees awarded to women in the Physical Sciences
plt.scatter(data['Age'], data['Income'], color='b')
plt.title('Scatter')
# Make the right subplot active in the current 1x2 subplot grid
plt.subplot(1, 2, 2)
# Plot in red the % of degrees awarded to women in Computer Science
plt.boxplot(data['Income'])
plt.title('Boxplot')
# Use plt.tight_layout() to improve the spacing between subplots
plt.tight_layout()
plt.show()g

Output

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 11/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

As shown in the output above, the figure is divided into two parts since row is one and the
columns are two. The scatterplot is generated in the first half and the boxplot is generated
in the second.

4. FacetGrid
Multiple plots can be created using subplots. However, several lines of code are needed to
create them. ‘Seaborn’ library is built on top of the ‘Matplotlib’ library, and it offers features
where custom graphics can be created in a single line of code. The ‘FacetGrid()’ function
can be used to create such plots.

The code below displays the scatter plot for age and income. This is done separately for
each value of the department.

sns.FacetGrid(col='Department',col_wrap=25,aspect=.8,size=4,data=data).map( \
plt.scatter, 'Age', 'Income')

Output

The output displays the scatter plot for age and income. This is done for groups of people
separated by the departments they work for.

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 12/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

The plots can be customised and the space between the graphs adjusted. The code below
demonstrates the same.

sns.FacetGrid(col='Department',col_wrap=50,aspect=1.2,size=4,data=data).map( \
plt.scatter, 'Age', 'Income', s=20).fig.subplots_adjust(wspace=.3, hspace=.2)

Output

5. Reading Images
The pyplot module of matplotlib can also be used to load an image and render it on screen.
The image is read using the ‘imread()’ function. The image is stored as pixel intensities in a
tuple. To display the image, the ‘imshow()’ function is used. Since, an image is being
displayed, it is good practice to turn off the axis. Else, the x and y axes will be rendered.

img = plt.imread(MAHE.png)
print(img.shape)
plt.imshow(img)
plt.axis('off')
plt.show()

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 13/14
SUBPLOTS, SCATTER PLOTS, AND READING IMAGES

Output
(1000, 1000, 4)

The ‘imread()’ function returns the image along with the number of rows, columns, and
channels. The number of channels is returned only if the image is coloured. If it is a grey
scale image, then the number of channels is not returned.

Besides ‘Matplotlib’, ‘OpenCV’ is another library in Python which provides functionalities to


handle images.

References:
• Mastering Python Data Visualization with Python by Kirthi Raman
• Python Data Visualization Cookbook by Igor Milovanović

©COPYRIGHT 2022 (Ver. 1.0), ALL RIGHTS RESERVED. MANIPAL ACADEMY OF HIGHER EDUCATION 14/14

You might also like