0% found this document useful (0 votes)
16 views

Lecture 9 - Data Visualization (Matplotlib)

Study material
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)
16 views

Lecture 9 - Data Visualization (Matplotlib)

Study material
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/ 26

Lecture 9 - Data Visualization (Matplotlib)

September 9, 2024

1 Data Visualization - Matplotlib


1.1 Matplotlib
• Extreme simplicity in its use
• Interactive data visualization
• Expressions and text in LaTeX
• Greater control over graphic elements
• Export to many formats, such as PNG, PDF, SVG, and EPS

1.2 Architecture - Matplotlib

1.3 Matplotlib - Artist layer

1
Artist Layer

1.4 Matplotlib - Scripting layer


code import matplotlib.pyplot as plt

[2]: import matplotlib.pyplot as plt


display(plt.plot([1,2,3,4]))
plt.show()

[<matplotlib.lines.Line2D at 0x22ecb73ac40>]

2
1.5 Default properties of plot
• The size of the axes matches perfectly with the range of the input data
• There is neither a title nor axis labels
• There is no legend
• A blue line connecting the points is drawn

[14]: plt.axis([0,5,0,20])
plt.title('My first plot')
plt.plot([1,2,3,4],[1,4,9,16], marker="o ", color='r')
#plt.plot([1,2,3,4],[1,4,9,16], 'ro-')

[14]: [<matplotlib.lines.Line2D at 0x28b1e90d730>]

3
[17]: # Adding labels to the axis
plt.axis([0,5,0,20])
plt.title('My first plot',fontsize=20,fontname='Times New Roman')
plt.xlabel('Counting',color='gray')
plt.ylabel('Square values',color='gray')
plt.plot([1,2,3,4],[1,4,9,16], marker="o", color='r')

[17]: [<matplotlib.lines.Line2D at 0x28b1eaae400>]

4
[60]: # Adding text within the plot
plt.axis([0,5,0,20])
plt.title('My first plot',fontsize=20,fontname='Times New Roman')
plt.xlabel('Counting',color='gray')
plt.ylabel('Square values',color='gray')
plt.text(2,4.5,'Second')
plt.text(3,9.5,'Third')
plt.plot([1,2,3,4],[1,4,9,16], marker="o", color='r', linestyle='-')
plt.legend(['First series'])

[60]: <matplotlib.legend.Legend at 0x22eda499ee0>

5
[5]: # Saving the figure
plt.savefig('my_chart.png')

<Figure size 640x480 with 0 Axes>

[75]: # Setting ticks


plt.axis([0,5,0,20])
plt.title('My first plot',fontsize=20,fontname='Times New Roman')
plt.xlabel('Counting',color='gray')
plt.ylabel('Square values',color='gray')
plt.plot([1,2,3,4],[1,4,9,16], marker="o", color='r', linestyle='-')
plt.yticks([0,5,10,15,20])
#plt.yticks([0,5,10,15,20], labels=['VL','L', 'M', 'H', 'VH'])

[75]: ([<matplotlib.axis.YTick at 0x22edcc41970>,


<matplotlib.axis.YTick at 0x22edcc41340>,
<matplotlib.axis.YTick at 0x22edccec490>,
<matplotlib.axis.YTick at 0x22edce7d370>,
<matplotlib.axis.YTick at 0x22edce7da30>],
[Text(0, 0, '0'),

6
Text(0, 5, '5'),
Text(0, 10, '10'),
Text(0, 15, '15'),
Text(0, 20, '20')])

[8]: # Multiple charts


import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2*np.pi,2*np.pi,0.01)
y1 = np.sin(3*x)/x
y2 = np.sin(2*x)/x
y3 = np.sin(4*x)/x
plt.plot(x,y1)
plt.plot(x,y2)
plt.plot(x,y3)
plt.legend(["first", "sec", "thi"])

[8]: <matplotlib.legend.Legend at 0x29cbd1917f0>

7
[76]: # Single figure. Multiple plots
# Two plots side by side
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)

[76]: [<matplotlib.lines.Line2D at 0x22edcb79370>]

8
1.6 Chart Typology
• Line Charts
• Scatter plots
• Histogram
• Bar charts
• Pie charts
• Polar charts

[7]: import matplotlib.pyplot as plt


import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)

[7]: <matplotlib.collections.PathCollection at 0x29cbe4d9a60>

9
[1]: # Histogram
import matplotlib.pyplot as plt
import numpy as np
pop = np.random.randint(0,100,100)
display(pop)
n,bins,patches = plt.hist(pop,bins=20)

array([79, 85, 55, 51, 44, 4, 29, 7, 98, 51, 22, 97, 31, 62, 67, 29, 75,
87, 85, 16, 19, 78, 16, 69, 6, 38, 62, 22, 82, 35, 83, 27, 22, 10,
69, 85, 0, 48, 2, 44, 21, 67, 11, 77, 43, 45, 25, 70, 36, 96, 15,
61, 8, 35, 40, 29, 84, 74, 14, 56, 98, 61, 11, 56, 8, 22, 72, 52,
34, 82, 12, 42, 73, 37, 23, 29, 62, 57, 17, 96, 77, 98, 38, 0, 12,
33, 93, 5, 47, 6, 19, 3, 34, 48, 44, 44, 66, 52, 78, 77])

10
[9]: # Bar Charts
import matplotlib.pyplot as plt
index = ['A', 'B', 'C', 'D', 'E']
values = [5,7,3,4,6]
plt.bar(index,values)

[9]: <BarContainer object of 5 artists>

11
[9]: # Bar Chart with error bars
# Bar Charts
import matplotlib.pyplot as plt
index = ['A', 'B', 'C', 'D', 'E']
values = [5,7,3,4,6]
std = [0.8,1,0.4,0.9,1.3]
plt.bar(index,values, yerr=std, capsize=36)

[9]: <BarContainer object of 5 artists>

12
[16]: # Horizontal bar charts
import matplotlib.pyplot as plt
index = ['A', 'B', 'C', 'D', 'E']
values = [5,7,3,4,6]
std = [0.8,1,0.4,0.9,1.3]
plt.barh(index,values, xerr=std, capsize=6)

[16]: <BarContainer object of 5 artists>

13
[33]: # Multi-series bar chart
import matplotlib.pyplot as plt
import numpy as np
index = np.arange(5)
values1 = [5,7,3,4,6]
values2 = [6,6,4,5,7]
values3 = [5,6,5,4,6]
wid = 0.3
plt.bar(index,values1,width=wid, color='b')
plt.bar(index+wid,values2,width=wid,color='g')
plt.bar(index+2*wid,values3,width=wid,color='r')

[33]: <BarContainer object of 5 artists>

14
[34]: # Multiseries stacked bar chart
import matplotlib.pyplot as plt
import numpy as np
series1 = np.array([3,4,5,3])
series2 = np.array([1,2,2,5])
series3 = np.array([2,3,3,4])
index = np.arange(4)
plt.bar(index,series1,color='r')
plt.bar(index,series2,color='b',bottom=series1)
plt.bar(index,series3,color='g',bottom=(series2+series1))

[34]: <BarContainer object of 4 artists>

15
[35]: import matplotlib.pyplot as plt
import numpy as np
index = np.arange(4)
series1 = np.array([3,4,5,3])
series2 = np.array([1,2,2,5])
series3 = np.array([2,3,3,4])
plt.barh(index,series1,color='r')
plt.barh(index,series2,color='g',left=series1)
plt.barh(index,series3,color='b',left=(series1+series2))

[35]: <BarContainer object of 4 artists>

16
[41]: # Multiseries stacked bar chart
import matplotlib.pyplot as plt
import numpy as np
series1 = np.array([3,4,5,3])
series2 = np.array([1,2,2,5])
series3 = np.array([2,3,3,4])
index = np.arange(4)
plt.bar(index,series1,color='w', hatch='xx')
plt.bar(index,series2,color='w',bottom=series1, hatch='//')
plt.bar(index,series3,color='w',bottom=(series2+series1),hatch='\\\\')

[41]: <BarContainer object of 4 artists>

17
[43]: # Pie-charts
import matplotlib.pyplot as plt
labels = ['Nokia','Samsung','Apple','Lumia']
values = [10,30,45,15]
colors = ['yellow','green','red','blue']
plt.pie(values,labels=labels,colors=colors)

[43]: ([<matplotlib.patches.Wedge at 0x22ed12e5b50>,


<matplotlib.patches.Wedge at 0x22ed12e5fd0>,
<matplotlib.patches.Wedge at 0x22ed12f5340>,
<matplotlib.patches.Wedge at 0x22ed12f5790>],
[Text(1.0461621663333946, 0.3399186987098808, 'Nokia'),
Text(-5.149471629032507e-08, 1.0999999999999988, 'Samsung'),
Text(-0.7778174228929385, -0.7778174957174645, 'Apple'),
Text(0.9801071906340714, -0.49938952218422467, 'Lumia')])

18
[44]: # Exploding pie chart
# Pie-charts
import matplotlib.pyplot as plt
labels = ['Nokia','Samsung','Apple','Lumia']
values = [10,30,45,15]
colors = ['yellow','green','red','blue']
explode= [0.3, 0, 0, 0]
plt.pie(values,labels=labels,colors=colors, explode=explode)

[44]: ([<matplotlib.patches.Wedge at 0x22ed133dbb0>,


<matplotlib.patches.Wedge at 0x22ed134a070>,
<matplotlib.patches.Wedge at 0x22ed134a4f0>,
<matplotlib.patches.Wedge at 0x22ed134a940>],
[Text(1.3314791207879568, 0.4326237983580301, 'Nokia'),
Text(-5.149471629032507e-08, 1.0999999999999988, 'Samsung'),
Text(-0.7778174228929385, -0.7778174957174645, 'Apple'),
Text(0.9801071906340714, -0.49938952218422467, 'Lumia')])

19
[45]: # Contour Plots
import matplotlib.pyplot as plt
import numpy as np
dx = 0.01; dy = 0.01
x = np.arange(-2.0,2.0,dx)
y = np.arange(-2.0,2.0,dy)
X,Y = np.meshgrid(x,y)
def f(x,y):
return (1 - y**5 + x**5)*np.exp(-x**2-y**2)
plt.contour(X,Y,f(X,Y),8,colors='black')

[45]: <matplotlib.contour.QuadContourSet at 0x22ed138ffa0>

20
[46]: # Contour Plots -- with labels
import matplotlib.pyplot as plt
import numpy as np
dx = 0.01; dy = 0.01
x = np.arange(-2.0,2.0,dx)
y = np.arange(-2.0,2.0,dy)
X,Y = np.meshgrid(x,y)
def f(x,y):
return (1 - y**5 + x**5)*np.exp(-x**2-y**2)
C = plt.contour(X,Y,f(X,Y),8,colors='black')
plt.clabel(C, inline=1)

[46]: <a list of 16 text.Text objects>

21
[50]: # Filled Contour Plots -- with labels
import matplotlib.pyplot as plt
import numpy as np
dx = 0.01; dy = 0.01
x = np.arange(-2.0,2.0,dx)
y = np.arange(-2.0,2.0,dy)
X,Y = np.meshgrid(x,y)
def f(x,y):
return (1 - y**5 + x**5)*np.exp(-x**2-y**2)
C = plt.contour(X,Y,f(X,Y),8,colors='black')
plt.contourf(X,Y,f(X,Y),8)
plt.clabel(C, inline=1)

[50]: <a list of 16 text.Text objects>

22
1.7 3-D plots
• 3D surfaces
• 3D scatter plots
• 3D bar charts

[1]: # 3D surface plots


import matplotlib.pyplot as plt
import numpy as np
plt.figure()
ax = plt.axes(projection='3d')
x = np.arange(-2,2,0.1)
y = np.arange(-2,2,0.1)
X,Y = np.meshgrid(x,y)
def f(x,y):
return (1 - y**5 + x**5)*np.exp(-x**2-y**2)

ax.plot_surface(X,Y,f(X,Y))

[1]: <mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x1a0c4f5d350>

23
[5]: # 3D scatter plots
import matplotlib.pyplot as plt
import numpy as np
s1_x = np.random.randint(30,40,100)
s1_y = np.random.randint(20,30,100)
s1_z = np.random.randint(10,20,100)
s2_x = np.random.randint(50,60,100)
s2_y = np.random.randint(30,40,100)
s2_z = np.random.randint(50,70,100)
plt.figure()
ax = plt.axes(projection='3d')
ax.scatter(s1_x,s1_y,s1_z)
ax.scatter(s2_x, s2_y, s2_z,c='r',marker='^')

[5]: <mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x1a0c75518d0>

24
[3]: # 3D bar charts
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(8)
y = np.random.randint(0,10,8)
y2 = y + np.random.randint(0,3,8)
y3 = y2 + np.random.randint(0,3,8)
y4 = y3 + np.random.randint(0,3,8)
y5 = y4 + np.random.randint(0,3,8)
clr = ['#4bb2c5', '#c5b47f', '#EAA228', '#579575', '#839557','#958c12',␣
↪'#953579', '#4b5de4']

plt.figure()
ax = plt.axes(projection='3d')
ax.bar(x,y,0,zdir='y',color=clr)
ax.bar(x,y2,10,zdir='y',color=clr)
ax.bar(x,y3,20,zdir='y',color=clr)
ax.bar(x,y4,30,zdir='y',color=clr)
ax.bar(x,y5,40,zdir='y',color=clr)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.view_init(elev=0)

25
26

You might also like