matplotlib
?¶matplotlib
is a 2D plotting library for Pythonimport matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Your goal is to plot the cosine and the sine functions on the same plot, using the default matplotlib
settings.
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
where,
plt.plot(x, c)
plt.plot(x, s)
plt.show()
[<matplotlib.lines.Line2D at 0x7f7e45b68a50>]
Rather than creating a plot with default size, we want to specify:
# Create a figure of size 8x6 inches, 80 dots per inch
plt.figure(figsize=(8, 6), dpi=80)
# Create a new subplot from a grid of 1x1
plt.subplot(1, 1, 1)
# Plot cosine with a blue continuous line of width 1 (pixels)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-")
# Plot sine with a green dotted line of width 1 (pixels)
plt.plot(x, s, color="green", linewidth=1.0, linestyle="dotted")
# Set x limits
plt.xlim(-4.0, 4)
# Set x ticks
plt.xticks(np.linspace(-4, 4, 9, endpoint=True))
# Set y limits
plt.ylim(-1.0, 1.0)
# Set y ticks
plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
([<matplotlib.axis.YTick at 0x7f7e453c7b50>, <matplotlib.axis.YTick at 0x7f7e453c72d0>, <matplotlib.axis.YTick at 0x7f7e45379a50>, <matplotlib.axis.YTick at 0x7f7e4537f9d0>, <matplotlib.axis.YTick at 0x7f7e4537fad0>], <a list of 5 Text yticklabel objects>)
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-")
plt.plot(x, s, color="red", linewidth=2.5, linestyle="solid")
[<matplotlib.lines.Line2D at 0x7f7e452171d0>]
Now, we want to space the axes to see all the data points
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-")
plt.plot(x, s, color="red", linewidth=2.5, linestyle="solid")
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(c.min() * 1.1, c.max() * 1.1)
(-1.1, 1.0999165211263138)
Current ticks are not ideal because they do not show the interesting values ($+/-\pi$, $+/-\pi/2$) for sine and cosine.
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-")
plt.plot(x, s, color="red", linewidth=2.5, linestyle="solid")
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(c.min() * 1.1, c.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, +1])
([<matplotlib.axis.YTick at 0x7f7e452adc10>, <matplotlib.axis.YTick at 0x7f7e452ad390>, <matplotlib.axis.YTick at 0x7f7e4529e9d0>], <a list of 3 Text yticklabel objects>)
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-")
plt.plot(x, s, color="red", linewidth=2.5, linestyle="solid")
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(c.min() * 1.1, c.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$'])
plt.yticks([-1, 0, +1], ['$-1$', '$0$', '$+1$'])
([<matplotlib.axis.YTick at 0x7f7e45304c10>, <matplotlib.axis.YTick at 0x7f7e452d71d0>, <matplotlib.axis.YTick at 0x7f7e453978d0>], <a list of 3 Text yticklabel objects>)
none
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-")
plt.plot(x, s, color="red", linewidth=2.5, linestyle="solid")
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(c.min() * 1.1, c.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$'])
plt.yticks([-1, 0, +1], ['$-1$', '$0$', '$+1$'])
ax = plt.gca() # 'get current axis'
# discard top and right spines
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-",
label="cosine")
plt.plot(x, s, color="red", linewidth=2.5, linestyle="solid",
label="sine")
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(c.min() * 1.1, c.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$'])
plt.yticks([-1, 0, +1], ['$-1$', '$0$', '$+1$'])
ax = plt.gca() # 'get current axis'
# discard top and right spines
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.legend(loc='upper right')
<matplotlib.legend.Legend at 0x7f7e451a4690>
annotate
command allows us to include annotation in the plotplt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(x, s, color="red", linewidth=2.5, linestyle="solid", label="sine")
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(c.min() * 1.1, c.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$'])
plt.yticks([-1, 0, +1], ['$-1$', '$0$', '$+1$'])
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points',
fontsize=16,
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3,rad=.2"))
plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5,
linestyle="--")
plt.scatter([t, ],[np.sin(t), ], 50, color='red')
plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
ax = plt.gca() # 'get current axis'
# discard top and right spines
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.legend(loc='upper left')
<matplotlib.legend.Legend at 0x7f7e4422bbd0>
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(x, s, color="red", linewidth=2.5, linestyle="solid", label="sine")
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(c.min() * 1.1, c.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$'])
plt.yticks([-1, 0, +1], ['$-1$', '$0$', '$+1$'])
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--")
plt.scatter([t, ],[np.sin(t), ], 50, color='red')
plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
ax = plt.gca() # 'get current axis'
# discard top and right spines
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.legend(loc='upper left')
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
n = 1024
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
t = np.arctan2(y, x)
plt.axes([0.025, 0.025, 0.95, 0.95])
plt.scatter(x, y, s=75, c=t, alpha=.5)
plt.xlim(-1.5, 1.5)
plt.xticks(())
plt.ylim(-1.5, 1.5)
plt.yticks(())
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
n = 12
xs = np.arange(n)
y1 = (1 - xs / float(n)) * np.random.uniform(0.5, 1.0, n)
y2 = (1 - xs / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.axes([0.025, 0.025, 0.95, 0.95])
plt.bar(xs, +y1, facecolor='#9999ff', edgecolor='white')
plt.bar(xs, -y2, facecolor='#ff9999', edgecolor='white')
for x, y in zip(xs, y1):
plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va= 'bottom')
for x, y in zip(xs, y2):
plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va= 'top')
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
## Images
image = np.random.rand(30, 30)
plt.imshow(image, cmap=plt.cm.hot)
plt.colorbar()
years, months, sales = np.loadtxt('data/carsales.csv', delimiter=',', skiprows=1, dtype=int, unpack=True)