Matplotlib

Basic plot

Initialization

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.plot(x,y,ls=”-.”,c=”black”,lw=2,label=”line1″)

ax.legend()
fig.tight_layout()

3D plot

from mpl_toolkits.mplot3d import Axes3D
ax = fig.add_subplot(1,1,1,projection="3d")
ax.scatter(x,y,z)

Contour plot

# suppose x,y,z are aligned scatter data
# ----
# notice python uses row major, so transpose is needed
cs = ax.contour(x,y,z.reshape(len(x),len(y)).T,colors="k")
# !! reshape(len(y),len(x)) is NOT correct, it jumbles data
ax.clabel(CS, fontsize=9, inline=1)
matplotlib.rcParams['contour.negative_linestyle'] = 'solid'

# for data not on a regular grid, use scipy.interpolate.griddata
# —-

# suppose the dataframe df contains x,y and vals
points = df[[“x”,”y”]].values
values = df.vals.values

# define desired grid
nx=10;ny=10;
finex = np.linspace(min(df.x),max(df.x),nx)
finey = np.linspace(min(df.y),max(df.y),ny)
fine_points = [[(x,y) for y in finey] for x in finex]
interp_data = griddata(points,values,fine_points)
cs = ax.contour(finex,finey,interp_data.reshape(nx,ny).T)

Formating

Change axis label format

from matplotlib.ticker import FormatStrFormatter
ax.get_xaxis().set_major_formatter( FormatStrFormatter("%1.2f") )

Customization

When I installed matplotlib on Ubuntu 16.04 with pip, there was a problem with the backend defaulting to “agg”, which has no graphical output. There might be a more elegant solution, but in my desperation I added the file ~/.config/matplotlib/matplotlibrc with “backend: Qt4Agg” and then installed all of pyqt4-dev-tools package, which solved the problem.