A Comprehensive Introduction to Python’s Matplotlib Plotting Library
This article provides a detailed tutorial on using Python’s Matplotlib library for creating high‑quality 2D and 3D visualizations, covering basic functions, advanced features like LaTeX support, color palettes, integration with IPython, and practical installation tips, all illustrated with code snippets and images.
Matplotlib is a powerful, open‑source Python plotting module that can produce high‑quality 2D and 3D graphics, handling scalar and vector data and exporting to formats such as EPS, PDF, SVG, PNG, and JPG.
Its API closely mirrors MATLAB’s, making the learning curve gentle for users familiar with MATLAB, and it is completely free.
Example of a filled area plot:
plt.fill(x, y1, 'b', x, y2, 'r', alpha=0.3)Example of a scatter plot:
plt.scatter(x, y, s=area, alpha=0.5)3‑D surface plotting can be done with just a few lines:
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)Streamlines and colorbars are also supported:
plt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)
plt.colorbar()A triplot example demonstrates custom markers and labeling:
plt.triplot(x, y, triangles, 'go-')
plt.title('triplot of user-specified triangulation')
plt.xlabel('Longitude (degrees)')
plt.ylabel('Latitude (degrees)')
ax = plt.subplot(111, polar=True)
bars = ax.bar(theta, radii, width=width, bottom=0.0)Matplotlib also supports LaTeX‑style equations in plots, and when combined with IPython Notebook the workflow becomes highly interactive.
For Windows users who find installation cumbersome, the portable WinPython distribution or the Anaconda distribution (which bundles most scientific and visualization libraries) are recommended.
Additional aesthetic enhancements can be achieved with color‑palette packages such as brewer2mpl and libraries like prettyplotlib . For statistical visualizations, Seaborn—built on top of Matplotlib—offers concise one‑line commands.
Further resources include Gist links with full source code, the Plotly interactive tutorial on nbviewer, and a collection of example images illustrating the capabilities of Matplotlib.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.