This is now recommended over %pylab inline
In [5]:
%matplotlib inline
This introduces matplotlib and pylab (probably among other things) to the namespace. We explicitly import everything else we need.
Because we are all responsible adults here, we ought to stick with the cleaner object-oriented interface pyplot (plt)
In [6]:
from matplotlib import pyplot as plt
In [7]:
import numpy as np
import pandas as pd
Use the following convenience function for plots for publication
In [8]:
def fig_size(fig_width_pt):
inches_per_pt = 1.0/72.27 # Convert pt to inch
golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt # width in inches
fig_height = fig_width*golden_mean # height in inches
return (fig_width, fig_height)
For a Latex document with \columnwidth 250 for example, we would use
In [9]:
params = {
'backend': 'ps',
'axes.labelsize': 10,
'text.fontsize': 10,
'legend.fontsize': 10,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'text.usetex': True,
'figure.figsize': fig_size(350.0)
}; params
Out[9]:
In [10]:
x = np.linspace(0, 5, 10)
y = x ** 2
With that, we are ready to make some plots
In [11]:
# for the publication-ready plots
with plt.rc_context(params):
fig, axes = plt.subplots()
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
fig.savefig('plot.eps')
In [12]:
# for regular plots for inline viewing
fig, axes = plt.subplots()
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
Out[12]:
In [13]:
# for xkcd style plots
with plt.xkcd():
fig, axes = plt.subplots()
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
Especially fond of the ability to make plots directly with pandas data structures
In [14]:
df = pd.DataFrame(np.random.randn(50, 4)); df
Out[14]:
In [15]:
# for the publication-ready plots
with plt.rc_context(params):
fig, axes = plt.subplots()
df.plot(ax=axes, style='o')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('a pretty random plot')
# fig.savefig('plot.eps')
In [ ]: