Matplotlib
In [7]: import matplotlib.pyplot as plt
In [9]: %matplotlib inline
In [11]: import numpy as np
In [47]: x = np.linspace(0,5,11)
y = x ** 2
In [34]: x
Out[34]: array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])
In [36]: y
Out[36]: array([ 0. , 0.25, 1. , 2.25, 4. , 6.25, 9. , 12.25, 16. ,
20.25, 25. ])
Functional Mathode :
In [38]: plt.plot(x,y)
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('Title')
plt.show()
In [40]: plt.subplot(1,2,1)
plt.plot(x,y,'r--')
plt.subplot(1,2,2)
plt.plot(y,x,'b--')
plt.show()
Object Oriented Method :
In [68]: fig = plt.figure()
axes = fig.add_axes([0.1,0.1,0.8,0.8])
axes.plot(x,y)
axes.set_xlabel('X Label')
axes.set_ylabel('Y Label')
axes.set_title('Object Oriented Method')
plt.show()
In [23]: fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.plot([1, 2, 3], [6, 5, 4])
ax.legend(["Line 1", "Line 2"])
plt.show()
In [42]: fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
ax2 = fig.add_axes([.2,.5,.4,.3])
ax1.plot(x,y)
ax1.set_title('Larger Plot')
ax2.plot(y,x)
ax2.set_title('Small plot')
plt.show()
subplots():
In [44]: fig, axes = plt.subplots()
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
plt.show()
In [98]: fig, axes = plt.subplots(nrows=1,ncols=2)
In [58]: for ax in axes:
ax.plot(x,y)
plt.show()
In [100… axes[0].plot(x,y)
axes[0].set_title('First plot')
axes[1].plot(y,x,'g--')
axes[1].set_title('Sceond plot')
plt.tight_layout()
plt.show()
In [124… fig ,axes = plt.subplots(ncols=1,nrows=2,figsize=(8,2))
axes[0].plot(x,y)
axes[1].plot(y,x,'g--')
plt.tight_layout()
plt.show()
In [134… fig.savefig('mypic.png',dpi=200)
In [164… fig = plt.figure(figsize =(3,2))
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y,label='am')
ax.plot(y,x,label= 'yu')
ax.legend(loc=(0.1,0.1))
plt.show()
In [242… fig = plt.figure(figsize =(3,2))
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y,color='#FF8C00',lw =4,alpha= 0.4,ls = '-',marker ='o',ms=10,
markerfacecolor='green',markeredgewidth =5,markeredgecolor='#8B008B')
plt.show()
In [24]: fig = plt.figure(figsize =(3,2))
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y,color='#FF8C00',lw =1,alpha= 0.5,ls = '--')
ax.set_xlim([0,1])
ax.set_ylim([0,2])
plt.show()
In [34]: plt.scatter(x,y)
plt.show()
In [56]: from random import sample
data = sample(range(1,100),10)
plt.hist(data)
plt.show()
In [60]: data = [np.random.normal(0, std, 100) for std in range(1, 4)]
plt.boxplot(data,vert=True,patch_artist=True)
plt.show()
Logarithmic scale:
In [19]: fig, axes = plt.subplots(1, 2, figsize=(10,4))
axes[0].plot(x, x**2, x, np.exp(x))
axes[0].set_title("Exponential Function")
axes[1].plot(x, x**2, x, np.exp(x))
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)")
plt.show()
Placement of ticks and custom tick labels:
In [28]: fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(x, x**2, x, x**3, lw=2)
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_xticklabels([r'$\alpha$', r'$\beta$', r'$\gamma$', r'$\delta$', r'$\epsilon$
yticks = [0, 50, 100, 150]
ax.set_yticks(yticks)
ax.set_yticklabels(["$%.1f$" % y for y in yticks], fontsize=18)
plt.grid(which='both', linestyle='--', linewidth=0.5)
plt.show()
Scientific notation :
In [37]: import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter
In [45]: x = np.linspace(1e-4, 1e4, 100)
y = x**2
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, y)
ax.ticklabel_format(style='sci', scilimits=(0, 0), axis='both')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.grid(True, which='both', linestyle='--', linewidth=0.5)
ax.yaxis.get_offset_text().set_fontsize(10)
plt.show()
Axis number and axis label spacing:
In [56]: x = np.linspace(0, 4, 100)
matplotlib.rcParams['xtick.major.pad'] = 10
matplotlib.rcParams['ytick.major.pad'] = 15
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, x**2, label="$x^2$")
ax.plot(x, np.exp(x), label="$e^x$")
ax.set_yticks([0, 50, 100, 150, 200])
ax.xaxis.labelpad = 20
ax.yaxis.labelpad = 30
ax.set_xlabel("x-axis", fontsize=12)
ax.set_ylabel("y-axis", fontsize=12)
ax.set_title("Custom Tick and Label Spacing", fontsize=14)
ax.legend()
plt.show()
Axis spines:
In [58]: fig, ax = plt.subplots(figsize=(6,2))
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('blue')
ax.spines['left'].set_color('red')
ax.spines['left'].set_linewidth(2)
ax.spines['right'].set_color("none")
ax.yaxis.tick_left()
plt.show()
Axes where x and y is zero :
In [62]: fig, ax = plt.subplots()
ax.spines['right'].set_color('none')
ax.spines['top'].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))
xx = np.linspace(-0.75, 1., 100)
ax.plot(xx, xx**3)
plt.show()
2D plot styles :
In [65]: n = np.array([0,1,2,3,4,5])
In [67]: fig, axes = plt.subplots(1, 4, figsize=(12,3))
axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx)))
axes[0].set_title("scatter")
axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")
axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[2].set_title("bar")
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
axes[3].set_title("fill_between")
plt.show()
Text annotation :
In [69]: fig, ax = plt.subplots()
ax.plot(xx, xx**2, xx, xx**3)
ax.text(0.15, 0.2, r"$y=x^2$", fontsize=20, color="blue")
ax.text(0.65, 0.1, r"$y=x^3$", fontsize=20, color="green")
plt.show()
subplot2grid :
In [73]: fig = plt.figure()
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2,0))
ax5 = plt.subplot2grid((3,3), (2,1))
fig.tight_layout()
plt.show()
Colormap and contour figures :
In [78]: alpha = 0.7
phi_ext = 2 * np.pi * 0.5
def flux_qubit_potential(phi_m, phi_p):
return 2 + alpha - 2 * np.cos(phi_p) * np.cos(phi_m) - alpha * np.cos(phi_ext -
In [80]: phi_m = np.linspace(0, 2*np.pi, 100)
phi_p = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T
In [82]: fig, ax = plt.subplots()
p = ax.pcolor(X/(2*np.pi), Y/(2*np.pi), Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min
cb = fig.colorbar(p, ax=ax)
plt.show()
In [84]: fig, ax = plt.subplots()
cnt = ax.contour(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(),
plt.show()
3D figures :
In [88]: from mpl_toolkits.mplot3d.axes3d import Axes3D
In [99]: fig = plt.figure(figsize=(14,6))
ax = fig.add_subplot(1, 2, 1, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, lin
cb = fig.colorbar(p, shrink=0.5)
plt.show()
In [97]: fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1, 1, 1, projection='3d')
p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)
plt.show()
In [101… fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*np.pi, cmap=matplotlib.cm.coolwarm)
ax.set_xlim3d(-np.pi, 2*np.pi);
ax.set_ylim3d(0, 3*np.pi);
ax.set_zlim3d(-np.pi, 2*np.pi)
plt.show()