100% found this document useful (1 vote)
3K views

Python Matplotlib Hands On

1) The document discusses creating line plots, scatter plots, bar plots, histograms, and box plots using Matplotlib in Python. Code examples are provided to generate a simple line plot, sine wave plot, multi-curve plot, scatter plot, bar plots of iris data, horizontal bar plot, histogram of normal distribution data, and boxplot of multiple normal distributions. 2) Functions are defined to generate each type of plot, which contain code for setting plot properties, adding data, labels, legends and saving figures. 3) The plots created cover common chart types and demonstrate basic usage of Matplotlib for data visualization.

Uploaded by

murugan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
3K views

Python Matplotlib Hands On

1) The document discusses creating line plots, scatter plots, bar plots, histograms, and box plots using Matplotlib in Python. Code examples are provided to generate a simple line plot, sine wave plot, multi-curve plot, scatter plot, bar plots of iris data, horizontal bar plot, histogram of normal distribution data, and boxplot of multiple normal distributions. 2) Functions are defined to generate each type of plot, which contain code for setting plot properties, adding data, labels, legends and saving figures. 3) The plots created cover common chart types and demonstrate basic usage of Matplotlib for data visualization.

Uploaded by

murugan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

My First Plot

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
#Write your code here
def test_my_first_plot():
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
t = [5, 10, 15, 20, 25]
d = [25, 50, 75, 100, 125]
ax.set(title='Time vs Distance Covered',
xlabel='time (seconds)', ylabel='distance (meters)',
xlim=(0, 30), ylim=(0,130))

m
er as
plt.plot(t, d, label='d = 5t')
plt.legend()

co
eH w
plt.savefig('scatter.png')
test_my_first_plot()

o.
rs e
ou urc
Create Line and Scatter Plots
import matplotlib
matplotlib.use('Agg')
o

import matplotlib.pyplot as plt


aC s

import numpy as np
vi y re

import matplotlib.gridspec as gridspec


import matplotlib.ticker as ticker
#Write your code here
def test_sine_wave_plot():
ed d

fig = plt.figure(figsize=(12,3))
ar stu

ax = fig.add_subplot(111)
t = np.linspace(0.0,2.0,200)
v = np.sin(2.5*np.pi*t)
is

plt.plot(t, v, label='sin(t)',color = 'red')


ax.set(title='Sine Wave', xlabel='Time (seconds)', ylabel='Voltage (mV)', xlim=(0, 2), ylim=(-1,1))
Th

xmajor = [0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8,2.0]
ymajor = [-1,0,1]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(xmajor))
ax.yaxis.set_major_formatter(ticker.FixedFormatter(ymajor))
sh

plt.grid(linestyle='--')
plt.legend()
plt.savefig('sinewave.png')
test_sine_wave_plot()

def test_multi_curve_plot():

This study source was downloaded by 100000790328255 from CourseHero.com on 06-27-2021 13:29:42 GMT -05:00

https://www.coursehero.com/file/76840785/Python-Matplotlib-hands-ondocx/
fig = plt.figure(figsize=(12,3))
ax = fig.add_subplot(111)
x = np.linspace(0.0,5.0,20)
y1 = x
y2 = x**2
y3 = x**3
ax.set(title='Linear, Quadratic, & Cubic Equations', xlabel='X', ylabel='f(x)')
ax.plot(x, y1, label='y=x',marker = 'o',color = 'red')
ax.plot(x, y2, label='y = x**2',marker = "s",color = 'green')
ax.plot(x, y3, label='y = x**3',marker = "^",color = 'blue')
plt.legend()
plt.savefig('multicurve.png')
test_multi_curve_plot()

def test_scatter_plot():
fig = plt.figure(figsize=(12,3))

m
ax = fig.add_subplot(111)

er as
s = [50, 60, 55, 50, 70, 65, 75, 65, 80, 90, 93, 95]

co
months = [1,2,3,4,5,6,7,8,9,10,11,12]

eH w
ax.set(title="Cars Sold by Company 'X' in 2017", xlabel='Months', ylabel='No. of Cars Sold',xlim=(0, 13),

o.
ylim=(20,100))

rs e
ax.scatter(months, s, marker = 'o', color = 'red')
ou urc
plt.xticks([1, 3, 5, 7, 9,11])
ax.set_xticklabels(['Jan', 'Mar', 'May', 'Jul', 'Sep', 'Nov'])
plt.savefig('scatter.png')
o

test_scatter_plot()
aC s

3 Bar Plots
vi y re

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ed d

import numpy as np
ar stu

import matplotlib.gridspec as gridspec


#Write your code here
def test_barplot_of_iris_sepal_length():
fig = plt.figure(figsize = (8,6))
is

ax = fig.add_subplot(111)
Th

species = ['setosa', 'versicolor', 'viriginica']


index = [0.2, 1.2, 2.2]
sepal_len = [5.01, 5.94, 6.59]
ax.set(title = "Mean Sepal Length of Iris Species",
sh

xlabel = "Specices",ylabel = "Sepal Length (cm)",


xlim = (0,3),ylim = (0,7))
ax.bar(index,sepal_len,width = 0.5,color = "red",edgecolor = "black")
plt.xticks([0.45,1.45,2.45])
ax.set_xticklabels(['setosa', 'versicolor', 'viriginica'])
ax.legend()

This study source was downloaded by 100000790328255 from CourseHero.com on 06-27-2021 13:29:42 GMT -05:00

https://www.coursehero.com/file/76840785/Python-Matplotlib-hands-ondocx/
plt.savefig('bar_iris_sepal.png')
test_barplot_of_iris_sepal_length()

def test_barplot_of_iris_measurements():
fig = plt.figure(figsize = (8,6))
ax = fig.add_subplot(111)
sepal_len = [5.01, 5.94, 6.59]
sepal_wd = [3.42, 2.77, 2.97]
petal_len = [1.46, 4.26, 5.55]
petal_wd = [0.24, 1.33, 2.03]
species = ['setosa', 'versicolor', 'viriginica']
species_index1 = [0.7, 1.7, 2.7]
species_index2 = [0.9, 1.9, 2.9]
species_index3 = [1.1, 2.1, 3.1]
species_index4 = [1.3, 2.3, 3.3]
ax.set(title = "Mean Measurements of Iris Species",xlabel = "Specices",ylabel = "Iris Measurements

m
(cm)",

er as
xlim = (0.5,3.7),ylim = (0,10))

co
ax.bar(species_index1, sepal_len, color='c', width=0.2, edgecolor='black', label='Sepal Length')

eH w
ax.bar(species_index2, sepal_wd, color='m', width=0.2, edgecolor='black', label='Sepal Width')

o.
ax.bar(species_index3, petal_len, color='y', width=0.2, edgecolor='black', label='Petal Length')

rs e
ax.bar(species_index4, petal_wd, color='orange', width=0.2, edgecolor='black', label='Petal Width')
ou urc
ax.set_xticks([1.1,2.1,3.1])
ax.set_xticklabels(['setosa', 'versicolor','viriginica'])
ax.legend()
o

plt.savefig('bar_iris_measure.png')
aC s

test_barplot_of_iris_measurements()
vi y re

def test_hbarplot_of_iris_petal_length():
fig = plt.figure(figsize = (12,5))
ed d

ax = fig.add_subplot(111)
species = ['setosa', 'versicolor', 'viriginica']
ar stu

index = [0.2, 1.2, 2.2]


petal_len = [1.46, 4.26, 5.55]
ax.set(title = "Mean Petal Length of Iris Species",ylabel = "Specices",xlabel = "Petal Length (cm)")
is

ax.barh(index, petal_len, color='c', height = 0.5, edgecolor='black', label='Sepal Length')


ax.set_yticks([0.45, 1.45,2.45])
Th

ax.set_yticklabels(['setosa', 'versicolor','viriginica'])
ax.legend()
plt.savefig('bar_iris_petal.png')
sh

test_hbarplot_of_iris_petal_length()

This study source was downloaded by 100000790328255 from CourseHero.com on 06-27-2021 13:29:42 GMT -05:00

https://www.coursehero.com/file/76840785/Python-Matplotlib-hands-ondocx/
4 Histograms and Box Plots
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
#Write your code here
def test_hist_of_a_sample_normal_distribution():
fig = plt.figure(figsize = (8,6))
ax = fig.add_subplot(111)
np.random.seed(100)
x1 = 25+3*np.random.randn(1000)
ax.set(title = "Histogram of a Single Dataset",xlabel = "x1",ylabel = "Bin Count")
ax.hist(x1,bins = 30)
plt.savefig('histogram_normal.png')

m
er as
test_hist_of_a_sample_normal_distribution()

co
eH w
def test_boxplot_of_four_normal_distribution():

o.
fig = plt.figure(figsize = (8,6))
ax = fig.add_subplot(111) rs e
ou urc
np.random.seed(100)
x1 = 25+3.0*np.random.randn(1000)
x2 = 35+5.0*np.random.randn(1000)
o

x3 = 55+10.0*np.random.randn(1000)
aC s

x4 = 45+3.0*np.random.randn(1000)
vi y re

ax.set(title = "Box plot of Multiple Datasets",xlabel = "Dataset",ylabel = "Value")


ax.boxplot([x1, x2, x3, x4], labels=['X1', 'X2', 'X3', 'X4'], notch=True,patch_artist = "True",showfliers =
"+")
plt.savefig('box_distribution.png')
ed d
ar stu

test_boxplot_of_four_normal_distribution()
is

5 Applying styles
Th

def test_generate_plot_with_style1():
fig = plt.figure(figsize = (8,6))
sh

ax = fig.add_subplot(111)
sepal_len = [5.01, 5.94, 6.59]
sepal_wd = [3.42, 2.77, 2.97]
petal_len = [1.46, 4.26, 5.55]
petal_wd = [0.24, 1.33, 2.03]
species = ['setosa', 'versicolor', 'viriginica']

This study source was downloaded by 100000790328255 from CourseHero.com on 06-27-2021 13:29:42 GMT -05:00

https://www.coursehero.com/file/76840785/Python-Matplotlib-hands-ondocx/
species_index1 = [0.7, 1.7, 2.7]
species_index2 = [0.9, 1.9, 2.9]
species_index3 = [1.1, 2.1, 3.1]
species_index4 = [1.3, 2.3, 3.3]
ax.set(title = "Mean Measurements of Iris Species",xlabel = "Specices",ylabel = "Iris Measurements
(cm)",
xlim = (0.5,3.7),ylim = (0,10))
ax.bar(species_index1, sepal_len, color='c', width=0.2, edgecolor='black', label='Sepal Length')
ax.bar(species_index2, sepal_wd, color='m', width=0.2, edgecolor='black', label='Sepal Width')
ax.bar(species_index3, petal_len, color='y', width=0.2, edgecolor='black', label='Petal Length')
ax.bar(species_index4, petal_wd, color='orange', width=0.2, edgecolor='black', label='Petal Width')
ax.set_xticks([1.1,2.1,3.1])
ax.set_xticklabels(['setosa', 'versicolor','viriginica'])
ax.legend()
plt.savefig('plotstyle1.png')
test_generate_plot_with_style1()

m
er as
co
6 Multiple Plots

eH w
o.
import matplotlib
matplotlib.use('Agg') rs e
ou urc
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
o

#Write your code here


aC s

def test_generate_figure1():
vi y re

fig = plt.figure(figsize=(8,6))
axes1 = plt.subplot(2, 1, 1, title='Sin(2*pi*x)')
axes2 = plt.subplot(2, 1, 2, title='Sin(4*pi*x)',sharex=axes1, sharey=axes1)
t = np.arange(0.0, 5.0, 0.01)
ed d

s1 = np.sin(2*np.pi*t)
ar stu

s2 = np.sin(4*np.pi*t)
axes1.plot(t, s1)
axes2.plot(t, s2)
plt.savefig('testfigure1.png')
is

test_generate_figure1()
Th

def test_generate_figure2():
fig = plt.figure(figsize = (8,6))
axes1 = plt.subplot(2,2,1,title = "Scatter plot with Upper Traingle Markers")
sh

plt.xticks([0.0, 0.4, 0.8, 1.2])


plt.yticks([-0.2, 0.2, 0.6, 1.0])
axes2 = plt.subplot(2,2,2,title = "Scatter plot with Plus Markers")
plt.xticks([0.0, 0.4, 0.8, 1.2])
plt.yticks([-0.2, 0.2, 0.6, 1.0])
axes3 = plt.subplot(2,2,3,title = "Scatter plot with Circle Markers")

This study source was downloaded by 100000790328255 from CourseHero.com on 06-27-2021 13:29:42 GMT -05:00

https://www.coursehero.com/file/76840785/Python-Matplotlib-hands-ondocx/
plt.xticks([0.0, 0.4, 0.8, 1.2])
plt.yticks([-0.2, 0.2, 0.6, 1.0])
axes4 = plt.subplot(2,2,4,title = "Scatter plot with Diamond Markers")
plt.xticks([0.0, 0.4, 0.8, 1.2])
plt.yticks([-0.2, 0.2, 0.6, 1.0])
np.random.seed(1000)
x = np.random.rand(10)
y = np.random.rand(10)
z = np.sqrt(x**2+y**2)
axes1.scatter(x,y, s = 80,c =z,marker = "^")
axes2.scatter(x,y, s = 80,c =z,marker = "+")
axes3.scatter(x,y, s = 80,c =z,marker = "o")
axes4.scatter(x,y, s = 80,c =z,marker = "d")
plt.tight_layout()
plt.savefig('testfigure2.png')
test_generate_figure2()

m
er as
def test_generate_figure3():

co
fig = plt.figure(figsize=(8,16))

eH w
g = gridspec.GridSpec(2,2)

o.
x = np.arange(0,101)
y1 = x
rs e
ou urc
y2 = x**2
y3 = x**3
axes1 = plt.subplot(g[0,:1],title='y = x')
o

axes2 = plt.subplot(g[1,:1], title='y = x**2')


axes3 = plt.subplot(g[:, 1], title='y = x**3')
aC s

axes1.plot(x, y1)
vi y re

axes2.plot(x, y2)
axes3.plot(x, y3)
plt.tight_layout()
ed d

plt.savefig('testfigure3.png')
test_generate_figure3()
ar stu
is
Th
sh

This study source was downloaded by 100000790328255 from CourseHero.com on 06-27-2021 13:29:42 GMT -05:00

https://www.coursehero.com/file/76840785/Python-Matplotlib-hands-ondocx/
Powered by TCPDF (www.tcpdf.org)

You might also like