Skip to content

Instantly share code, notes, and snippets.

@abehmiel
Created March 31, 2017 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abehmiel/77c27fef6acf1f37366717937efc26d4 to your computer and use it in GitHub Desktop.
Save abehmiel/77c27fef6acf1f37366717937efc26d4 to your computer and use it in GitHub Desktop.
Matplotlib subplots with TeX rendering: good figure baseline for publications
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fig = plt.figure(figsize=(8.5,11.0))
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.rcParams['text.latex.preamble'] = [r'\boldmath']
# data in xmn, ymn does not exist. Replace with whatever data you're trying to plot
ax = fig.add_subplot(111)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
#ax = axs[0, 0]
ax1.plot(x11, y11, 'sk', label=r'\textbf{label1}', markersize=12)
ax1.plot(x12, y12, 'og', label=r'\textbf{label2}', markersize=12)
ax1.plot(x13, y13, 'dr', fillstyle='bottom', label=r'\textbf{label3}', markersize=12)
ax1.plot(x14, y14, '^b', fillstyle='bottom', label=r'\textbf{label4}', markersize=12)
ax1.set_xlabel(r'\textbf{X-axis label}', fontsize=16)
#ax1.set_ylabel(r'\textbf{Y-axis label}', fontsize=16)
ax1.set_title(r"\textbf{Plot title}", fontsize=16)
#ax = axs[0, 1]
ax2.plot(x21, y21, 'sk', label=r'\textbf{label1}', markersize=12)
ax2.plot(x22, y22, 'og', label=r'\textbf{label2}', markersize=12)
ax2.plot(x23, y23, 'dr', fillstyle='bottom', label=r'\textbf{label3}', markersize=12)
ax2.plot(x24, y24, '^b', fillstyle='bottom', label=r'\textbf{label4}', markersize=12)
ax2.set_xlabel(r'\textbf{X-axis}', fontsize=16)
#ax2.set_ylabel(r'\textbf{Y-axis}', fontsize=16)
ax2.set_title(r"\textbf{Plot title}", fontsize=16)
fig.tight_layout()
i = 0
j = [r"\textbf{text1}", r"\textbf{text2}"]
for axis in [ax1, ax2]:
s = j[i]
i += 1
axis.annotate(s, xy=(0.450, 0.080), xycoords='axes fraction', fontsize=16,
horizontalalignment='left', verticalalignment='top')
plt.setp(axis.get_xticklabels(), fontsize=16)
plt.setp(axis.get_yticklabels(), fontsize=16)
# change extent of plot to prevent everything from sliding off the edge
box = axis.get_position()
axis.set_position([box.x0 *(1.5), box.y0, box.width*0.95, box.height*0.94])
for subaxis in ['top','bottom','left','right']:
axis.spines[subaxis].set_linewidth(2.0)
# remove axis
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
# common y-axis label
ax.set_ylabel(r'\textbf{Shared y-axis label}', fontsize=20)
ax1.legend(loc='lower right', fontsize=16)
plt.savefig('fig1.png')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment