import numpy as np
import matplotlib.pyplot as plt
import matplotlib
%matplotlib notebook
When writing a paper, a beautiful figure is very important. Before, I used Gnuplot or XMGRACE to make figures because it is easy to config.
Recently I moved to Matplotlib and used it in many of my projects, found it convenient to make plots and tweak them to produce beautiful figures.
Here are some snippet for reference to easily look back.
Import library
Config for matplotlib
# config for matplotlib
= {'family' : 'arial',
font 'weight' : 'normal',
'size' : 12}
'font', **font)
matplotlib.rc('axes.spines.right'] = False
matplotlib.rcParams['axes.spines.top'] = False
matplotlib.rcParams['axes.linewidth'] = 2 #set the value globally
matplotlib.rcParams[
# set tick width
'xtick.major.size'] = 6
matplotlib.rcParams['xtick.major.width'] = 2
matplotlib.rcParams['ytick.major.size'] = 6
matplotlib.rcParams['ytick.major.width'] = 2 matplotlib.rcParams[
# Create a fake data:
= np.arange(0, 2*np.pi, 2*np.pi/1000)
x = np.sin(x)
y = np.cos(x) y2
= plt.figure(figsize=(8,5))
fig ='black', lw=2, label='sin(x)', alpha=0.8)
plt.plot(x,y, color='red', lw=2, label='cos(x)', alpha=0.8)
plt.plot(x,y2, color
# Plot horizontal
= 0.0, color = 'blue', linestyle = '--', alpha=0.5)
plt.axhline(y
# Config Legends and labels
# set yticks
-1, 0, 1], ['first', 'second', ''])
plt.yticks([
='upper center', ncol=2)
plt.legend(loc0, 2*np.pi)
plt.xlim(-1,1)
plt.ylim(r'$f_x$') #latex type
plt.ylabel('x')
plt.xlabel(
# To save figure with high DPI, uncomment following line: the more dpi, the clearer figure but large file
# plt.savefig('Demo_matplotlib.png', dpi=1200)
Text(0.5, 0, 'x')
Plot with error bars
Reading data:
= np.loadtxt('data/cat3.dat') cat3
1st column will be used as x-location
2nd column: observed value.
3rd column: lower bound (95% CI)
4th column: upper bound (95% CI)
Data looks like:
!cat data/cat3.dat
#percent, 1: Refold, 2: WT, 3: S, 4:F
1 38 29 47
2 27 18 36
3 35 26 44
4 9 4 15
= plt.subplots(figsize=(5, 3))
fig2, ax2 0], cat3[:,1],'*', markersize=15)
ax2.plot(cat3[:,= [cat3[:,1]-cat3[:,2], cat3[:,3]-cat3[:,1]]
cat3_yerr 0], cat3[:,1], yerr=cat3_yerr, fmt='none', color='black', elinewidth=2, capsize=10, capthick=2)
plt.errorbar(cat3[:,1, 2, 3, 4], ['Refold', 'WT', 'SLOW', 'FAST'], fontweight="bold")
plt.xticks([list(range(0, 51, 10)))
plt.yticks(1, 51)
plt.ylim(0.2, 4.2)
plt.xlim('Percent of folded trajs', fontweight="bold")
plt.ylabel(# plt.savefig('CAT3_all_variants.png', dpi=1200)
Text(0, 0.5, 'Percent of folded trajs')