[go: up one dir, main page]

0% found this document useful (0 votes)
58 views9 pages

AD3301 - Unit II - Part 1 .Ipynb - Colaboratory

The document discusses various techniques for plotting graphs in Python using the Matplotlib library. It covers topics like setting styles, creating subplots, saving figures, adjusting line colors and styles, labeling plots, and creating scatter plots. Examples are provided to demonstrate how to generate simple line plots, add titles and labels, control the plot area, and customize properties of points in scatter plots. The document aims to introduce the basics of data visualization in Python.

Uploaded by

palaniappan.cse
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)
58 views9 pages

AD3301 - Unit II - Part 1 .Ipynb - Colaboratory

The document discusses various techniques for plotting graphs in Python using the Matplotlib library. It covers topics like setting styles, creating subplots, saving figures, adjusting line colors and styles, labeling plots, and creating scatter plots. Examples are provided to demonstrate how to generate simple line plots, add titles and labels, control the plot area, and customize properties of points in scatter plots. The document aims to introduce the basics of data visualization in Python.

Uploaded by

palaniappan.cse
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/ 9

10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .

ipynb - Colaboratory

Importing matplotlib

import matplotlib.pyplot as plt


import numpy as np
import random

Setting Styles in graphs

print(plt.style.available)

data = np.random.randn(50)
data

randn() function creates an array of specified shape and fills it with random values as per
standard normal distribution

#plt.style.use('Solarize_Light2')
plt.style.use('dark_background')
#plt.style.use('ggplot')
plt.plot(data)

plt.show doesn't make any differences in notebooks such as colab, jupyter or spyder

plt.show is required to display if we are running the code on IDLE

Two Interfaces for the Price of One

plt.subplot(2, 1, 1)
plt.plot(data)

plt.subplot(2, 1, 2)
plt.plot(data)

subplot(nrows, ncols, index)


https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 1/9
10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .ipynb - Colaboratory

plt.subplot(1, 2, 1) the figure has 1 row, 2 columns, and this plot is the first plot.

plt.subplot(1, 2, 2) the figure has 1 row, 2 columns, and this plot is the second plot

index should be = No.of Rows * No.of.Columns

Saving Figures to File

Saving the file and downloading in Colab

In other notebooks the file will be saved in the working directory

from google.colab import files


plt.savefig("abc.png")
files.download("abc.png")

Object-oriented interface

plt.figure() is used to create a figure object

Mainly used when we want to fix the size of the figure and when we want to add multiple Axes
objects in a single figure.

#fig = plt.figure(figsize=(7,4)) #Optional code


fig, ax_lst = plt.subplots(3) # returns a tuple containing figure and axes object(s)
ax_lst[0].plot(data)
ax_lst[1].plot(data)
ax_lst[2].plot(data)

plt.subplots() is a function that returns a tuple containing a figure and axes object(s). plt.figure()
and plt.axes(). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables
fig and ax

#Alternate method

fig = plt.figure()
ax = plt.axes()

Simple Line Plots

https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 2/9
10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .ipynb - Colaboratory

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# Plot between -10 and 10 with .001 steps.


x_axis = np.arange(-100, 100, 0.01)

plt.style.use('ggplot')
plt.plot(x_axis)

# Alternate method
fig = plt.figure()
ax = plt.axes()

#Calculating mean and standard deviation


mean = np.mean(x_axis)
sd = np.std(x_axis)
y_axis = norm.pdf(x_axis, mean, sd)
ax.plot(x_axis, y_axis)

Adjusting the Plot: Line Colors and Styles

Line Style

You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line:

fig = plt.figure()
ax = plt.axes()
ax.plot(x_axis, norm.pdf(x_axis, mean, sd),linestyle = 'dotted')
ax.plot(x_axis, norm.pdf(x_axis+10, mean, sd),linestyle = 'solid')
ax.plot(x_axis, norm.pdf(x_axis+20, mean, sd),linestyle = 'dashed')
ax.plot(x_axis, norm.pdf(x_axis+30, mean, sd),linestyle = 'dashdot')

The above picture has mutiple plot in single display

Line Color

You can use the keyword argument color or the shorter c to set the color of the line:

fig = plt.figure()
ax = plt.axes()
ax.plot(x_axis, norm.pdf(x_axis, mean, sd),linestyle = 'dotted',c = 'r')
ax.plot(x_axis, norm.pdf(x_axis+10, mean, sd),linestyle = 'solid',c = 'b')

https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 3/9
10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .ipynb - Colaboratory

ax.plot(x_axis, norm.pdf(x_axis+20, mean, sd),linestyle = 'dashed',c = 'g')


ax.plot(x_axis, norm.pdf(x_axis+30, mean, sd),linestyle = 'dashdot',c = 'hotpink')

Suppose if we would like to truncate that view, into a smaller one or even a larger one, we can
tweak the X and Y limits. These can be accessed either through the PyPlot instance, or the Axes
instance.

plt.plot(x_axis, norm.pdf(x_axis, mean, sd))


#plt.xlim(-75,75)
#plt.ylim(0,0.01)
plt.axis([-75,75,0,0.02])

plt.plot(x_axis, norm.pdf(x_axis, mean, sd))


plt.axis("tight")

plt.plot(x_axis, norm.pdf(x_axis, mean, sd))


plt.axis("equal")

Labeling Plots

#Adding a title to the graph

fig = plt.figure()
ax = plt.axes()

#Calculating mean and standard deviation


mean = np.mean(x_axis)
sd = np.std(x_axis)
ax.plot(x_axis, norm.pdf(x_axis, mean, sd),linestyle = 'dotted')
plt.title("A normal curve")

Add labels to the x- and y-axis

fig = plt.figure()
ax = plt.axes()
ax.plot(x_axis, norm.pdf(x_axis, mean, sd),linestyle = 'dotted')
plt.title("A normal curve")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")

Adding legend and labeling multiple line in a graph

fig = plt.figure()
ax = plt.axes()

https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 4/9
10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .ipynb - Colaboratory

ax.plot(x_axis, norm.pdf(x_axis+10, mean, sd),linestyle = 'dotted',c = 'g', label = 'x-axi


ax.plot(x_axis, norm.pdf(x_axis+20, mean, sd),linestyle = 'dashed',c = 'b', label = 'x-axi
ax.plot(x_axis, norm.pdf(x_axis+30, mean, sd),linestyle = 'dashdot',c = 'r', label = 'x-ax
plt.title("A normal curve")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.legend()

Scatter plots

a graph in which the values of two variables are plotted along two axes, the pattern of the
resulting points revealing any correlation present.

No_of_games = [3,5,2,6,7,1,2,7,1,7,3]
score = [80,90,75,80,90,50,65,85,40,100,95]

Score = np.array(score)
No_of_Games = np.array(No_of_games)
print(Score,No_of_Games)

Plot the graph with

X-axis or horizontal axis: Number of games

Y-axis or vertical axis: Scores

plt.plot(No_of_Games,Score,'x',c = 'b')

fig = plt.figure()
ax = plt.axes()

ax.plot(No_of_Games,Score,'x',c = 'b')

https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 5/9
10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .ipynb - Colaboratory

marker = ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']
for i in range(len(No_of_Games)):
plt.plot(No_of_Games+i,Score+10,marker[i])

For even more possibilities, these character codes can be used together with line and color
codes to plot points along with a line connecting them

plt.plot(No_of_Games,Score,'-ok',c = 'b')

plt.plot(No_of_Games,Score,'-p', color='red',
markersize=25, linewidth=4,
markerfacecolor='white',
markeredgecolor='gray',
markeredgewidth=2)

Scatter Plots with plt.scatter

plt.scatter(No_of_Games,Score,marker = 'x')

The difference between the two functions is:

with pyplot.plot() any property you apply

(color, shape, size of points)

will be applied across all points whereas in pyplot.

scatter() you have more control in each point’s appearance

colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80])
sizes = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80])

plt.scatter(No_of_Games,Score,c=colors, s=sizes, cmap='Accent_r')

#plt.colorbar()

https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 6/9
10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .ipynb - Colaboratory

import matplotlib.pyplot as plt


import numpy as np
from sklearn.datasets import load_diabetes
dia = load_diabetes()
features = dia.data.T

print(dia.feature_names)

https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 7/9
10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .ipynb - Colaboratory

Try Plotting coloumn

0 and 2

0 and 3

4 and 5

6 and 7

plt.scatter(features[5], features[7], alpha=0.3,


s=100*features[0], c=dia.target, cmap='viridis')
plt.xlabel(dia.feature_names[5])
plt.ylabel(dia.feature_names[7])

https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 8/9
10/3/22, 12:10 PM AD3301 - Unit II - Part 1 .ipynb - Colaboratory

Colab paid products - Cancel contracts here

https://colab.research.google.com/drive/1dtwey0Sn8I_wscPjMMaC64rUirSgMAjN#printMode=true 9/9

You might also like