import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sympy
x = np.linspace(-5, 2, 100)
y1 = x**3 + 5*x**2 + 10
y2 = 3*x**2 + 10*x
y3 = 6*x + 10
fig, ax = plt.subplots()
ax.plot(x, y1, color="blue", label="y(x)")
ax.plot(x, y2, color="red", label="y'(x)")
ax.plot(x, y3, color="green", label="y”(x)")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
fig.savefig("graph.png", dpi=300, facecolor="#f1f1f1")
fig, ax = plt.subplots(2,2)
ax[0,0].plot(x, y1, color="blue", label="y(x)")
ax[0,1].plot(x, y2, color="red", label="y'(x)")
ax[1,0].plot(x, y3, color="green", label="y”(x)")
ax[1,1].plot(x, y3, color="green", label="y”(x)")
[<matplotlib.lines.Line2D at 0x7faa594448b0>]
x = np.linspace(-5, 5, 5)
y = np.ones_like(x)
def axes_settings(fig, ax, title, ymax):
ax.set_xticks([])
ax.set_yticks([])
ax.set_ylim(0, ymax+1) # range of y-axis
ax.set_title(title)
fig, axes = plt.subplots()
linewidths = [0.5, 1.0, 2.0, 4.0]
for n, linewidth in enumerate(linewidths):
#return the index and component
axes.plot(x, y + n, color="blue", linewidth=linewidth)
axes_settings(fig, axes, "linewidth", len(linewidths))
fig, axes = plt.subplots()
# Line style
linestyles = ['-', '-.', ':', '--']
for n, linestyle in enumerate(linestyles):
axes.plot(x, y + n, color="blue", lw=2,
linestyle=linestyle)
fig, axes = plt.subplots()
# marker types
markers = ['+', 'o', '*', 's', '.', '1', '2', '3', '4']
for n, marker in enumerate(markers):
# lw = shorthand for linewidth, ls = shorthand for linestyle
axes.plot(x, y + n, color="blue", lw=2, ls='',
marker=marker)
axes_settings(fig, axes, "markers", len(markers))
fig, axes = plt.subplots()
# marker size and color
markersc = [(4, "white"), (8, "red"),
(12, "yellow"), (16, "lightgreen")]
for n, (markersize, markerfacecolor) in enumerate(markersc):
axes.plot(x, y + n, color="black", lw=1, ls='-',
marker='o', markersize=markersize,
markerfacecolor=markerfacecolor, markeredgewidth=2)
axes_settings(fig, axes, "marker size/color",
len(markersc))
x = np.linspace(-5, 2, 100)
y1 = x**3 + 5*x**2 + 10
y2 = 3*x**2 + 10*x
y3 = 6*x + 10
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(x, y1, color="blue", label="y(x)", linewidth =4)
ax.plot(x, y2, color="red", label="y'(x)", linestyle=':')
ax.plot(x, y3, color="black", label="y”(x)", linestyle='-.')
ax.set_xlabel("x")
ax.set_ylabel("y")
# place a legend outsize of the Axes
ax.legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.0)
# loc = 2 means "upper left"
# make room for the legend to the right of the Axes
fig.subplots_adjust(right=.75)
fig.savefig("graph.png", dpi=300, facecolor="#f1f1f1")
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(x, y1, color="blue", label="y(x)", linewidth =4)
ax.plot(x, y2, color="red", label="y'(x)", linestyle=':')
ax.plot(x, y3, color="black", label="y”(x)", linestyle='-.')
ax.set_xlabel("x")
ax.set_ylabel("y")
# place a legend outsize of the Axes
ax.legend(loc=2)
# loc = 1, 2, 3, 4
<matplotlib.legend.Legend at 0x7faa28254730>
fig, ax = plt.subplots()
ax.plot(x, y1, color="blue", label="y(x)", linewidth =4)
ax.plot(x, y2, color="red", label="y'(x)", linestyle=':')
ax.plot(x, y3, color="black", label="y”(x)", linestyle='-.')
ax.set_xlabel("x")
ax.set_ylabel("y")
# place a legend outsize of the Axes
ax.legend(ncol=3, loc=3, bbox_to_anchor=(0, 1))
fig.subplots_adjust(top=.5)
fig, ax = plt.subplots(figsize=(12, 2))
ax.set_yticks([])
ax.set_xticks([])
ax.set_xlim(-0.5, 3.5)
ax.set_ylim(-0.05, 0.25)
ax.axhline(0)
# text label
ax.text(0, 0.1, "Text label", fontsize=14, family="serif")
# annotation
ax.plot(1, 0, "o")
ax.annotate("Annotation", fontsize=14, family="serif",
xy=(1, 0), xycoords="data", xytext=(+20, +50),
textcoords="offset points",
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3, rad=.5"))
# equation
ax.text(2, 0.1,
r"Equation: $i\hbar\partial_t \Psi = \hat{H}\Psi$",
fontsize=14, family="serif")
Text(2, 0.1, 'Equation: $i\\hbar\\partial_t \\Psi = \\hat{H}\\Psi$')
x = np.linspace(0, 50, 500)
y = np.sin(x) * np.exp(-x/10)
fig, ax = plt.subplots(figsize=(8, 2),
subplot_kw={'facecolor':"#ebf5ff"})
ax.plot(x, y, lw=2)
ax.set_xlabel("x", labelpad=5, fontsize=18,
fontname='serif', color="blue")
ax.set_ylabel("f(x)", labelpad=15, fontsize=18,
fontname='serif', color="blue")
ax.set_title("axis labels and title example",
fontsize=16, fontname='serif', color="blue")
Text(0.5, 1.0, 'axis labels and title example')
x = np.linspace(0, 30, 500)
y = np.sin(x) * np.exp(-x/10)
fig, axes = plt.subplots(1, 3, figsize=(9, 2),
subplot_kw={'facecolor': "#ebf5ff"})
axes[0].plot(x, y, lw=2)
axes[0].set_xlim(-5, 35)
axes[0].set_ylim(-1, 1)
axes[1].plot(x, y, lw=2)
axes[1].axis('tight')
axes[2].plot(x, y, lw=2)
axes[2].axis('equal')
(-1.5, 31.5, -0.701557219454465, 0.9328577492890343)
x = np.linspace(-2 * np.pi, 2 * np.pi, 500)
y = np.sin(x) * np.exp(-x**2/20)
fig, axes = plt.subplots(1, 2, figsize=(6, 2))
axes[0].plot(x, y, lw=2)
axes[0].set_title("default ticks")
axes[1].plot(x, y, lw=2)
axes[1].set_title("set_xticks")
axes[1].set_yticks([-1, 0, 1])
axes[1].set_xticks([-5, 0, 5])
[<matplotlib.axis.XTick at 0x7faa4b584fd0>, <matplotlib.axis.XTick at 0x7faa4b5840a0>, <matplotlib.axis.XTick at 0x7faa4b584e50>]
fig, axes = plt.subplots(figsize=(6, 2))
axes.plot(x, y, lw=2)
axes.set_title("set_major_locator")
axes.xaxis.set_major_locator(mpl.ticker.MaxNLocator(3))
axes.yaxis.set_major_locator(
mpl.ticker.FixedLocator([-1, 0, 1]))
axes.xaxis.set_minor_locator(mpl.ticker.MaxNLocator(8))
axes.yaxis.set_minor_locator(mpl.ticker.MaxNLocator(8))
fig, axes = plt.subplots(figsize=(6, 2))
axes.plot(x, y, lw=2)
axes.set_title("set_xticklabels")
axes.set_yticks([-1, 0, 1])
axes.set_xticks([-2 * np.pi, -np.pi, 0, np.pi, 2 * np.pi])
axes.set_xticklabels([r'$-2\pi$', r'$-\pi$', 0,
r'$\pi$',r'$2\pi$'])
x_minor_ticker = mpl.ticker.FixedLocator([-3 * np.pi / 2,
-np.pi / 2, 0,
np.pi / 2,
3 * np.pi / 2])
axes.xaxis.set_minor_locator(x_minor_ticker)
axes.yaxis.set_minor_locator(mpl.ticker.MaxNLocator(4))
# we omit the setting grid
fig, axes = plt.subplots(1, 3, figsize=(12, 2))
x = np.linspace(0, 1e3, 100)
y1, y2 = x**3, x**4
axes[0].set_title('loglog')
axes[0].loglog(x, y1, 'b', x, y2, 'r')
axes[1].set_title('semilogy') # y-axis has log scale
axes[1].semilogy(x, y1, 'b', x, y2, 'r')
axes[2].set_title('plot / set_xscale / set_yscale')
axes[2].plot(x, y1, 'b', x, y2, 'r')
axes[2].set_xscale('log')
axes[2].set_yscale('log')
r = np.linspace(0, 5, 100)
a = 4 * np.pi * r ** 2 # area
v = (4 * np.pi / 3) * r ** 3 # volume
fig, ax1 = plt.subplots(figsize=(8, 3))
ax1.set_title("surface area and volume of a sphere",
fontsize=16)
ax1.set_xlabel("radius [m]", fontsize=16)
ax1.plot(r, a, lw=2, color="blue")
ax1.set_ylabel(r"surface area ($m^2$)",
fontsize=16, color="blue")
for label in ax1.get_yticklabels():
label.set_color("blue")
ax2 = ax1.twinx()
ax2.plot(r, v, lw=2, color="red")
ax2.set_ylabel(r"volume ($m^3$)", fontsize=16, color="red")
for label in ax2.get_yticklabels():
label.set_color("red")
def f(x):
return 1/(1 + x**2) + 0.1/(1 + ((3 - x)/0.1)**2)
def plot_and_format_axes(ax, x, f, fontsize):
ax.plot(x, f(x), linewidth=2)
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(5))
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(4))
ax.set_xlabel(r"$x$", fontsize=fontsize)
ax.set_ylabel(r"$f(x)$", fontsize=fontsize)
fig = plt.figure(figsize=(8, 3))
# main graph
ax = fig.add_axes([0.1, 0.15, 0.8, 0.8], facecolor="#f5f5f5")
x = np.linspace(-4, 14, 1000)
plot_and_format_axes(ax, x, f, 18)
# inset
x0, x1 = 2.5, 3.5
ax.axvline(x0, ymax=0.3, color="grey", linestyle=":")
ax.axvline(x1, ymax=0.3, color="grey", linestyle=":")
ax_insert = fig.add_axes([0.5, 0.5, 0.38, 0.42],
facecolor='none')
x = np.linspace(x0, x1, 1000)
plot_and_format_axes(ax_insert, x, f, 14)
x = y = np.linspace(-10, 10, 150)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.cos(Y) * np.exp(-(X/5)**2-(Y/5)**2)
fig, ax = plt.subplots(figsize=(6, 3))
norm = mpl.colors.Normalize(-abs(Z).max(), abs(Z).max())
p = ax.pcolor(X, Y, Z, norm=norm, cmap=mpl.cm.bwr)
ax.axis('tight')
ax.set_xlabel(r"$x$", fontsize=18)
ax.set_ylabel(r"$y$", fontsize=18)
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(4))
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(4))
cb = fig.colorbar(p, ax=ax)
cb.set_label(r"$z$", fontsize=18)
cb.set_ticks([-1, -.5, 0, .5, 1])
fig, ax = plt.subplots(figsize=(6, 3))
aa = np.arange(0,1.001,0.001)
yy = np.arange(0,1.001,0.001)
a,y=np.meshgrid(aa,yy)
#a, y =np.mgrid[0:0.01:1, 0:0.01:1]
z0 = a**3-y**2
ax.set_xlim(np.min(a),np.max(a))
ax.set_ylim(np.min(y),np.max(y))
ax.contour(a, y, z0, levels=0)
<matplotlib.contour.QuadContourSet at 0x7faa4b265850>