import numpy as np
import matplotlib.pyplot as plt
import matplotlib
%matplotlib notebookWhen 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
font = {'family' : 'arial',
'weight' : 'normal',
'size' : 12}
matplotlib.rc('font', **font)
matplotlib.rcParams['axes.spines.right'] = False
matplotlib.rcParams['axes.spines.top'] = False
matplotlib.rcParams['axes.linewidth'] = 2 #set the value globally
# set tick width
matplotlib.rcParams['xtick.major.size'] = 6
matplotlib.rcParams['xtick.major.width'] = 2
matplotlib.rcParams['ytick.major.size'] = 6
matplotlib.rcParams['ytick.major.width'] = 2# Create a fake data:
x = np.arange(0, 2*np.pi, 2*np.pi/1000)
y = np.sin(x)
y2 = np.cos(x)fig = plt.figure(figsize=(8,5))
plt.plot(x,y, color='black', lw=2, label='sin(x)', alpha=0.8)
plt.plot(x,y2, color='red', lw=2, label='cos(x)', alpha=0.8)
# Plot horizontal
plt.axhline(y = 0.0, color = 'blue', linestyle = '--', alpha=0.5)
# Config Legends and labels
# set yticks
plt.yticks([-1, 0, 1], ['first', 'second', ''])
plt.legend(loc='upper center', ncol=2)
plt.xlim(0, 2*np.pi)
plt.ylim(-1,1)
plt.ylabel(r'$f_x$') #latex type
plt.xlabel('x')
# 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:
cat3 = np.loadtxt('data/cat3.dat')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
fig2, ax2 = plt.subplots(figsize=(5, 3))
ax2.plot(cat3[:,0], cat3[:,1],'*', markersize=15)
cat3_yerr = [cat3[:,1]-cat3[:,2], cat3[:,3]-cat3[:,1]]
plt.errorbar(cat3[:,0], cat3[:,1], yerr=cat3_yerr, fmt='none', color='black', elinewidth=2, capsize=10, capthick=2)
plt.xticks([1, 2, 3, 4], ['Refold', 'WT', 'SLOW', 'FAST'], fontweight="bold")
plt.yticks(list(range(0, 51, 10)))
plt.ylim(1, 51)
plt.xlim(0.2, 4.2)
plt.ylabel('Percent of folded trajs', fontweight="bold")
# plt.savefig('CAT3_all_variants.png', dpi=1200)Text(0, 0.5, 'Percent of folded trajs')