How to create charts with matplotlib
· Category: Data Science
Short answer
Matplotlib is the foundational Python plotting library that provides fine-grained control over every element of a chart.
Steps
- Import matplotlib.pyplot and prepare data as arrays or pandas Series.
- Create a figure and axes with plt.subplots for explicit control.
- Plot data using functions like plot, bar, scatter, or hist.
- Add labels, titles, legends, and annotations to communicate meaning.
- Save the figure to a file with savefig before showing or closing.
Tips
- Use the object-oriented interface for complex multi-panel figures.
- Set global styles with plt.style.use for consistent aesthetics.
- Customize color cycles and markers for accessibility and clarity.
- Vector formats like PDF or SVG preserve quality for publication.
Common issues
- Overlapping labels and titles when figure size is too small.
- Forgetting to call show in interactive environments or scripts.
- Color maps that are not perceptually uniform or colorblind-friendly.
- Memory leaks from creating too many figures without closing them.
Example
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style='whitegrid')
plt.figure(figsize=(10, 6))
sns.barplot(x='category', y='value', data=df)
plt.title('Sales by Category')
plt.show()
This snippet demonstrates how to configure aesthetics and create a publication-ready bar chart with labeled axes and a clear title.