Matplotlib Tutorial Python: Plot Your Data in Minutes
This matplotlib tutorial python guide walks through the essentials of creating, customizing, and saving charts with Matplotlib. You will build a line plot, a grouped bar chart, and a multi-panel figure while learning the patterns that scale to real projects. The examples use only Matplotlib and standard Python data structures so you can follow along without extra dependencies.
More from this site
Keep reading the latest coverage
Why Matplotlib Matters for Python Developers
Matplotlib is the foundation for most Python visualization work. Pandas plots, Seaborn, and many scientific libraries call Matplotlib under the hood. Understanding it directly gives you control over every element of a figure, from axis ticks to legend placement. It is the go-to library when a chart must match a journal style, a dashboard specification, or a precise layout requirement that higher-level tools cannot easily satisfy.
Installation and First Plot
Install Matplotlib in your environment with pip or conda:
- pip install matplotlib
- conda install matplotlib
Once installed, a minimal script produces a line chart in seconds:
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 1, 5, 3] plt.plot(x, y) plt.xlabel('X axis') plt.ylabel('Y axis') plt.title('First Plot') plt.show()The plt.show() call opens a window with the rendered figure. Until that line runs, nothing is displayed. This interactive mode works well in scripts and standalone Python files. In Jupyter notebooks, use the magic command %matplotlib inline to render plots directly in the cell output.
Plot Types You Will Use Most
Matplotlib supports dozens of chart types. The following are the ones that appear in most data workflows:
- Line plots (plt.plot) — show trends over time or a continuous variable.
- Bar charts (plt.bar, plt.barh) — compare categories.
- Scatter plots (plt.scatter) — reveal relationships and outliers between two variables.
- Histograms (plt.hist) — display the distribution of a single variable.
- Pie charts (plt.pie) — show proportions of a whole.
- Stacked area plots (plt.stackplot) — visualize how parts contribute to a total over time.
Styling and Customization
Matplotlib separates data from presentation. You can control line color, marker style, line width, and transparency with keyword arguments:
plt.plot(x, y, color='steelblue', marker='o', linewidth=2, markersize=8, alpha=0.85)For consistent styling across many figures, use a style sheet or update the rcParams dictionary:
plt.style.use('seaborn-v0_8-whitegrid') plt.rcParams.update({'font.size': 12, 'figure.dpi': 150})The built-in style list includes ggplot, classic, bmh, and dark_background. Choosing a style once at the start of your script changes the default appearance of every subsequent plot.
Subplots and Multi-Panel Figures
Use plt.subplots to create a grid of axes in a single figure call. It returns a figure object and an array of axes:
fig, axes = plt.subplots(2, 2, figsize=(10, 6)) axes[0, 0].plot(x, y) axes[0, 0].set_title('Top Left') axes[0, 1].scatter(x, y) axes[1, 0].bar(x, y) axes[1, 1].hist(y) plt.tight_layout() plt.show()The tight_layout() call automatically adjusts spacing so labels and titles do not overlap. For more control over the grid, use gridspec_kw or the object-oriented GridSpec class.
Annotations, Legends, and Text
Highlight specific data points with plt.annotate:
plt.annotate('Peak', xy=(4, 5), xytext=(3, 5.5), arrowprops=dict(arrowstyle='->', color='gray'))Add a legend by passing a label to each plot call and then invoking plt.legend(). Position the legend with the loc parameter, for example loc='upper left' or loc='best'.
Saving Figures
Use fig.savefig to export a figure to a file without displaying it on screen:
fig.savefig('my_plot.png', dpi=300, bbox_inches='tight')Supported formats include PNG, PDF, SVG, and EPS. For publications, PDF and SVG produce vector graphics that remain sharp at any zoom level. The bbox_inches='tight' argument trims excess whitespace around the figure.
Common Mistakes to Avoid
- Calling plt.plot repeatedly without clearing the figure can overlay data unintentionally.
- Using the stateful interface in complex scripts makes it hard to track which axes a command applies to.
- Forgetting figsize can produce figures that are too small or too wide for a report layout.
- Omitting plt.show() in a script means the figure window never appears.
Next Steps
With these fundamentals in place, you can explore object-oriented interfaces for more complex layouts, integrate Matplotlib with Pandas DataFrames, and build custom colormaps for heatmaps and contour plots. The official Matplotlib gallery contains hundreds of reproducible examples that serve as templates for your own work.