Introductory Notes: Matplotlib: Preliminaries
Introductory Notes: Matplotlib: Preliminaries
Preliminaries
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
1
Build a line plot with Matplotlib and raw (x, y) data Build a multi-line plot from raw data in matplotlib
A single line plot in matplotlib A multi-line plot with markers and line-styles
# --- fake up some data # --- select a style
x = np.linspace(0, 4*np.pi, 800) plt.style.use('classic')
y = np.sin(x)
# --- get the Figure and Axes all at once
# --- Select a style fig, ax = plt.subplots(figsize=(8,6))
plt.style.use('classic')
# --- plot some lines
# --- get an empty Figure and add an Axes N = 8 # the number of lines we will plot
fig = plt.figure(figsize=(8,4)) styles = ['-', '--', '-.', ':']
ax = fig.add_subplot(1,1,1) # row-col-num markers = list('+ox^psDv')
x = np.linspace(0, 100, 20)
# --- line plot data on the Axes for i in range(N): # add line-by-line
ax.plot(x, y, 'b-', linewidth=2, y = x + x/5*i + i
label=r'$y=\sin(x)$') s = styles[i % len(styles)]
m = markers[i % len(markers)]
# --- add title and axis labels ax.plot(x, y,
ax.set_title('The Sine Wave') label='Line '+str(i+1)+' '+s+m,
ax.set_ylabel(r'$y$', fontsize=16) marker=m, linewidth=2, linestyle=s)
ax.set_xlabel(r'$x$', fontsize=16)
# --- add grid, legend, title and save
# --- change the default plot limits ax.grid(True)
ax.set_xlim((-0.05, 4*np.pi + 0.05,)) ax.legend(loc='best', prop={'size':'large'})
ax.set_ylim((-1.05, 1.05)) ax.set_title('A Simple Line Plot')
fig.tight_layout(pad=1)
# --- plot a legend in the best location fig.savefig('filename.png', dpi=125)
ax.legend(loc='best') plt.close('all')
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
2
Scatter plots – using matplotlib's ax.scatter()
Use seaborn
import seaborn as sns
x = np.random.randn(100)
y = x + np.random.randn(100) + 10
df = DataFrame([x, y], index=['x', 'y']).T
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
3
Changing the marker symbol
Scatter plots – more options
# --- get the Figure and Axes classes
plt.style.use('classic')
Changing the marker size and colour fig, ax = plt.subplots(figsize=(8,8))
# --- import a colour map
import matplotlib.cm as cm # --- add scatter plots
markers = list('ov^<>12348sphHdD+x*|_')
# --- get some data N = len(markers)
N = 100 for i, m in enumerate(markers):
x = np.random.rand(N) x = np.arange(N)
y = np.random.rand(N) y = np.repeat(i+1, N)
size = ((np.random.rand(N) + 1) * 8) ** 2 ax.scatter(x, y, marker=m, label=m,
colour = np.random.rand(N) s=50, c='cornflowerblue')
ax.set_xlim((-0.05, 1.05))
ax.set_ylim((-0.05, 1.05))
fig.tight_layout(pad=1);
fig.savefig('filename6.png', dpi=125)
plt.close('all')
Note: there are many colormaps to choose from.
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
4
Bar plots – using ax.bar() and ax.barh()
As nice as pie
# --- get some data
data = np.array([5,3,4,6])
labels = ['bats', 'cats', 'gnats', 'rats']
explode = (0, 0.1, 0, 0) # explode cats
colrs=['khaki', 'goldenrod', 'tan', 'wheat']
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
6
Spines in the middle
Plot spines
# --- the data
x = np.linspace(-np.pi, np.pi, 800)
Hiding the top and right spines y = np.sin(x)
# --- the data
x = np.linspace(-np.pi, np.pi, 800) # --- the plot
y = np.sin(x) fig, ax = plt.subplots(figsize=(8, 4))
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
7
Legend to the right of the plot
Legends
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(8, 4))
Legend within the plot
Use the 'loc' argument to place the legend x = np.arange(N)
# --- get the empty Figure and Axes classes for j in range(5):
plt.style.use('classic') ax.plot(x, x*(j+1),
fig, ax = plt.subplots(figsize=(8, 4)) label='Line '+str(j))
N = 5
x = np.arange(N)
for j in range(5):
Legend slightly outside of the plot ax.plot(x, x*(j+1),
plt.style.use('classic') label='Line '+str(j))
fig, ax = plt.subplots(figsize=(8, 4))
N = 5 fig.tight_layout(pad=1)
x = np.arange(N) box = ax.get_position()
for j in range(5): ax.set_position([box.x0,
ax.plot(x, x*(j+1), box.y0 + box.height * 0.15,
label='Line '+str(j)) box.width, box.height * 0.85])
ax.legend(bbox_to_anchor=(0.5, -0.075),
ax.legend(bbox_to_anchor=(1.05, 1.05)) loc='upper center', ncol=N)
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
8
Using GridSpec layouts (like list slicing)
Multiple plots on a canvas
import matplotlib.gridspec as gs
gs = gs.GridSpec(3, 3) # nrows, ncols
Using Axes to place a plot within a plot fig = plt.figure(figsize=(8,3))
fig = plt.figure(figsize=(8,3)) fig.text(x=0.01, y=0.01, s='Figure',
fig.text(x=0.01, y=0.01, s='Figure', color='#888888', ha='left',
color='#888888', ha='left', va='bottom', fontsize=20)
va='bottom', fontsize=20) ax1 = fig.add_subplot(gs[0, :]) # row,col
ax1.text(x=0.2,y=0.2,s='0, :', color='b')
# --- Main Axes ax2 = fig.add_subplot(gs[1,:-1])
ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax2.text(x=0.2,y=0.2,s='1, :-1', color='b')
ax.text(x=0.01, y=0.01, s='Main Axes', ax3 = fig.add_subplot(gs[1:, -1])
color='red', ha='left', va='bottom', ax3.text(x=0.2,y=0.2, s='1:, -1', color='b')
fontsize=20) ax4 = fig.add_subplot(gs[-1,0])
ax.set_xticks([]); ax.set_yticks([]) ax4.text(x=0.2,y=0.2, s='-1, :0', color='b')
ax5 = fig.add_subplot(gs[-1,-2])
# --- Insert Axes ax5.text(x=0.2,y=0.2, s='-1,:-2', color='b')
ax= fig.add_axes([0.15,0.65,0.2,0.2]) for a in fig.get_axes():
ax.text(x=0.01, y=0.01, s='Insert Axes', a.set_xticks([])
color='blue', ha='left', va='bottom', a.set_yticks([])
fontsize=20)
ax.set_xticks([]); ax.set_yticks([]) fig.suptitle('GridSpec Layout')
fig.suptitle('An Axes within an Axes') fig.savefig('filename.png', dpi=125)
fig.savefig('filename.png', dpi=125) plt.close('all')
plt.close('all')
for i in range(4):
# fig.add_subplot(nrows, ncols, num)
ax = fig.add_subplot(2, 2, i+1)
ax.text(x=0.01, y=0.01,
s='Subplot 2 2 '+str(i+1),
color='red', ha='left',
va='bottom', fontsize=20)
ax.set_xticks([]); ax.set_yticks([])
ax.set_xticks([]); ax.set_yticks([])
fig.suptitle('Subplots')
fig.savefig('filename.png', dpi=125)
plt.close('all')
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
9
Style Roll your own style sheet
grid.linestyle: -
grid.linewidth: 0.5
grid.color: e7e7e7
xtick.major.size: 0
xtick.minor.size: 0
xtick.labelsize: small
xtick.color: 333333
ytick.major.size: 0
ytick.minor.size: 0
ytick.labelsize: small
ytick.color: 333333
figure.figsize: 8, 4 # inches
figure.facecolor: white
text.color: black
savefig.edgecolor: white
savefig.facecolor: white
Which is saved as "markgraph.mplstyle"
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
10
Cautionary notes
Version 19 May 2017 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
11