MATPLOTLIB Tutorial
from matplotlib import pylab
print(pylab.__version__)
1.20.3
"""Use NumPy to generate random data
"""
import numpy as np
x = np.linspace(0, 10, 25)
y = x * x + 2
print(x)
print(y)
[ 0. 0.41666667 0.83333333 1.25 1.66666667 2.08333333 2.5 2.91666667 3.33333333 3.75 4.16666667 4.58333333 5. 5.41666667 5.83333333 6.25 6.66666667 7.08333333 7.5 7.91666667 8.33333333 8.75 9.16666667 9.58333333 10. ]
[ 2. 2.17361111 2.69444444 3.5625 4.77777778 6.34027778 8.25 10.50694444 13.11111111 16.0625 19.36111111 23.00694444 27. 31.34027778 36.02777778 41.0625 46.44444444 52.17361111 58.25 64.67361111 71.44444444 78.5625 86.02777778 93.84027778 102. ]
"""It takes only one command to draw
"""
pylab.plot(x, y, 'r') # 'r' stands for red
[<matplotlib.lines.Line2D at 0x2068905ebb0>]
"""Drawing a subgraph
一个绘图区域可以画多个子图,下面是画2个1x2的子图,1图起点在从左上角起(1, 2),2图起点在从左上角起(2, 2)
"""
pylab.subplot(1, 2, 1) # The contents of the brackets represents (rows, columns, indexes)
pylab.plot(x, y, 'r--') # The third parameter here determines color and line style
pylab.subplot(1, 2, 2)
pylab.plot(y, x, 'g*-')
[<matplotlib.lines.Line2D at 0x24316f90730>]
#(1, 2, 1) and (1, 2, 2) are signoficant if we want tiled subplots, without which both the graphs will in the same plot
#for example
pylab.subplot(1, 2, 1) # The contents of the brackets represents (rows, columns, indexes)
pylab.plot(x, y, 'r--') # The third parameter here determines color and line style
pylab.subplot(1, 2, 1)
pylab.plot(y, x, 'g*-')
[<matplotlib.lines.Line2D at 0x20689802fd0>]
Operator Description
fig.add_axes() = Initialize subplot a = fig.add_subplot(222)
fig, b = plt.subplots(nrow = 3, ncols = 2) = Adds subplot
ax = plt.subplots(2, 2) = Create subplot
from matplotlib import pyplot as plt
fig = plt.figure()
axis = fig.add_axes([0.5, 0.1, 0.8, 0.8]) # Control the left, right, width, height of the canvas (from 0 to 1)
axis.plot(x, y, 'r')
[<matplotlib.lines.Line2D at 0x2068ae1efd0>]
# again we can draw subgraphs
fig, axes = plt.subplots(nrows = 1, ncols = 2) # Submap is of 1 row, 2 columns
for ax in axes:
ax.plot(x, y, 'r')
# we can also draw a picture, or graph, inside another graph
fig = plt.figure()
# Control the left, right, width, height of the canvas (from 0 to 1)
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # big axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # small canvas
axes1.plot(x, y, 'r')
axes2.plot(y, x, 'g')
[<matplotlib.lines.Line2D at 0x2068b16cdf0>]
fig = plt.figure(figsize=(16, 9), dpi=100) # Create graphic object
ax1 = fig.add_subplot()
plt.plot(x, y, 'r')
[<matplotlib.lines.Line2D at 0x20690ca8c10>]
ax.legend(['label1', 'label2'])
fig, axes = plt.subplots()
axes.set_xlabel('x-label')
axes.set_ylabel('y-label')
axes.set_title('title of graph')
axes.plot(x, x**2)
axes.plot(x, x**3)
axes.legend(['y = x**2', 'y = x**3'], loc=2)
<matplotlib.legend.Legend at 0x20696b2dee0>
# In matplotlab, you can set other properties such as line color, transparency, and more
fig, axes = plt.subplots(dpi=150)
axes.plot(x, x**2, color = 'red', alpha = .5)
axes.plot(x, x + 2, color = '#1155dd', alpha = .5)
axes.plot(x, x + 3, color = '#15cc55', alpha = .5)
[<matplotlib.lines.Line2D at 0x20699171b20>]
fig, axes = plt.subplots(dpi=100)
# line width
axes.plot(x, x + 1, 'b', linewidth=.25)
axes.plot(x, x + 2, 'b', linewidth=1)
axes.plot(x, x + 3, 'b', linewidth=1.5)
axes.plot(x, x + 4, 'b', linewidth=2)
[<matplotlib.lines.Line2D at 0x20696d37160>]
fig, axes = plt.subplots(dpi=100)
# line width
axes.plot(x, x + 1, 'b', lw=2, linestyle='-')
axes.plot(x, x + 2, 'b', lw=2, linestyle='-.')
axes.plot(x, x + 3, 'b', lw=2, linestyle=':')
line, = axes.plot(x, x + 4, 'black', lw=1.50)
line.set_dashes([5, 10, 15, 10])
line, = axes.plot(x, x + 5, 'black', lw=1.50)
line.set_dashes([5, 10, 15, 3])
line, = axes.plot(x, x + 6, 'black', lw=1.50)
line.set_dashes([5, 10, 4, 10])
fig, ax = plt.subplots(dpi=100)
ax.plot(x, x + 1, color='blue', marker='o')
ax.plot(x, x + 2, color='blue', marker='+')
ax.plot(x, x + 3, color='blue', marker='s')
ax.plot(x, x + 4, color='blue', marker='1')
ax.plot(x, x + 5, color='blue', marker='o', markersize=2)
ax.plot(x, x + 6, color='blue', marker='s', markerfacecolor='red')
ax.plot(x, x + 7, color='blue', marker='o', markersize=8, markerfacecolor='green')
[<matplotlib.lines.Line2D at 0x2069bf32af0>]
"""Set the canvas grid and axis range
"""
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].plot(x, x**2, x, x**3, lw=2)
axes[0].grid(True)
axes[1].plot(x, x**2, x, x**3, lw=2)
axes[1].set_ylim([0, 60])
axes[1].set_xlim([2, 5])
axes[1].grid(True)
Other 2D Graphics
n = np.array([0, 1, 2, 3, 4, 5])
fig, axes = plt.subplots(1, 4, figsize = (16, 5))
axes[0].set_title('scatter')
axes[0].scatter(x, x + 0.25*np.random.randn(len(x)))
axes[1].set_title('step')
axes[1].step(n, n**2, lw=2)
axes[2].set_title('bar')
axes[2].bar(n, n**2, align='center', width=0.5, alpha=0.5)
axes[3].set_title('fill_between')
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5)
<matplotlib.collections.PolyCollection at 0x1d490472c40>
"""Draw a radar chart
"""
fig = plt.figure(figsize=(6, 6))
ax = fig.add_axes([0, 0, 0.6, 0.6], polar = True)
t = np.linspace(0, 2*np.pi, 100)
ax.plot(t, t, color='blue', lw=3)
[<matplotlib.lines.Line2D at 0x1d48e95b700>]
"""Draw a histogram
"""
n = np.random.randn(100000)
fig, axes = plt.subplots(1, 2, figsize = (12, 4))
axes[0].set_title('Default histogram')
axes[0].hist(n)
axes[1].set_title('Cumulative detailed histogram')
axes[1].hist(n, cumulative=True, bins=50)
(array([1.0000e+00, 2.0000e+00, 2.0000e+00, 3.0000e+00, 7.0000e+00, 1.6000e+01, 3.6000e+01, 6.5000e+01, 1.2500e+02, 2.2900e+02, 4.3100e+02, 7.3900e+02, 1.2210e+03, 1.9490e+03, 3.0650e+03, 4.6220e+03, 6.7240e+03, 9.6150e+03, 1.3206e+04, 1.7836e+04, 2.3198e+04, 2.9459e+04, 3.6171e+04, 4.3526e+04, 5.1027e+04, 5.8458e+04, 6.5785e+04, 7.2550e+04, 7.8415e+04, 8.3632e+04, 8.7903e+04, 9.1318e+04, 9.3883e+04, 9.5843e+04, 9.7335e+04, 9.8310e+04, 9.8956e+04, 9.9380e+04, 9.9650e+04, 9.9819e+04, 9.9887e+04, 9.9935e+04, 9.9966e+04, 9.9981e+04, 9.9988e+04, 9.9995e+04, 9.9997e+04, 9.9998e+04, 9.9999e+04, 1.0000e+05]),
array([-4.74285772, -4.55213386, -4.36140999, -4.17068613, -3.97996227, -3.7892384 , -3.59851454, -3.40779067, -3.21706681, -3.02634294, -2.83561908, -2.64489521, -2.45417135, -2.26344748, -2.07272362, -1.88199975, -1.69127589, -1.50055203, -1.30982816, -1.1191043 , -0.92838043, -0.73765657, -0.5469327 , -0.35620884, -0.16548497, 0.02523889, 0.21596276, 0.40668662, 0.59741049, 0.78813435, 0.97885821, 1.16958208, 1.36030594, 1.55102981, 1.74175367, 1.93247754, 2.1232014 , 2.31392527, 2.50464913, 2.695373 , 2.88609686, 3.07682073, 3.26754459, 3.45826845, 3.64899232, 3.83971618, 4.03044005, 4.22116391, 4.41188778, 4.60261164, 4.79333551]),
<BarContainer object of 50 artists>)
# Draw contour image
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
ax.clabel(CS, inline=1, fontsize=10)
ax.set_title('contour map')
Text(0.5, 1.0, 'contour map')
# Draw 3D surface image
from mpl_toolkits.mplot3d.axes3d import Axes3D
fig = plt.figure(figsize=(14, 6))
# Specify the 3D graphics to draw, with projection='3d'
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, lw=0)
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x1d4908799d0>
# heatmap.... color map
Practice Example
Write a Python programming to create a pie chart of the popularity of programming languages
import matplotlib .pyplot as plt
# Data to plot
languages = 'Python', 'Java', 'PHP', 'JavaScript', 'C#', 'C++'
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
# explode 1st slice
explode = (0.1, 0, 0, 0, 0, 0)
plt.pie(popularity, explode=explode, labels=languages, colors=colors,
autopct='1%.1f%%', shadow=True, startangle=140)
([<matplotlib.patches.Wedge at 0x1d491d87340>,
<matplotlib.patches.Wedge at 0x1d491d87cd0>,
<matplotlib.patches.Wedge at 0x1d491d926d0>,
<matplotlib.patches.Wedge at 0x1d491d9f0a0>,
<matplotlib.patches.Wedge at 0x1d491d9fa30>,
<matplotlib.patches.Wedge at 0x1d491dad400>],
[Text(-1.1518739051683529, -0.33643202373170245, 'Python'),
Text(0.5025192070582963, -0.978506232242545, 'Java'),
Text(1.0971674240514186, 0.07889007288863878, 'PHP'),
Text(0.754341041824552, 0.8006057660415953, 'JavaScript'),
Text(0.06701830757132049, 1.0979565321315212, 'C#'),
Text(-0.5993297985645449, 0.9223902604389219, 'C++')],
[Text(-0.6719264446815391, -0.19625201384349306, '131.3%'),
Text(0.2741013856681616, -0.5337306721322972, '124.8%'),
Text(0.5984549585735011, 0.043030948848348426, '112.4%'),
Text(0.41145875008611926, 0.4366940542045065, '111.3%'),
Text(0.036555440493447534, 0.5988853811626479, '110.8%'),
Text(-0.3269071628533881, 0.5031219602394119, '19.4%')])