Search Knowledge

© 2026 LIBREUNI PROJECT

Python for Scientific Computing / Data Visualization Deep Dive

Matplotlib: Styling and Customization

Plotting for Publication

Scientists don’t just produce plots; they produce evidence. A good plot should be clear, accessible, and aesthetically pleasing. In this lesson, we explore how to move beyond default settings.

Global Styles with plt.style

Matplotlib comes with several pre-defined style sheets. You can view them all using plt.style.available.

python
1 
2import matplotlib.pyplot as plt
3import numpy as np
4 
5# Use a clean, modern style
6plt.style.use('ggplot')
7 
8x = np.random.randn(100)
9y = np.random.randn(100)
10 
11fig, ax = plt.subplots()
12ax.scatter(x, y, alpha=0.5, color='purple')
13ax.set_title('Styled Scatter Plot')
14 
15plt.show()
16 

Working with Colormaps

Choosing the right colormap is critical. Avoid “jet” and other non-perceptually uniform maps. Use viridis, magma, or inferno for continuous data.

python
1 
2import matplotlib.pyplot as plt
3import numpy as np
4 
5x = np.linspace(0, 5, 100)
6y = np.linspace(0, 5, 100)
7X, Y = np.meshgrid(x, y)
8Z = np.sin(X)**10 + np.cos(10 + Y*X) * np.cos(X)
9 
10fig, ax = plt.subplots()
11im = ax.imshow(Z, origin='lower', extent=[0, 5, 0, 5], cmap='viridis')
12fig.colorbar(im, label='Intensity')
13ax.set_title('Perceptually Uniform Colormap')
14 
15plt.show()
16 

Annotations: Highlighting Key Data

Sometimes you need to point directly at a feature in your data.

python
1 
2import matplotlib.pyplot as plt
3import numpy as np
4 
5fig, ax = plt.subplots()
6 
7t = np.arange(0.0, 5.0, 0.01)
8s = np.cos(2*np.pi*t)
9ax.plot(t, s, lw=2)
10 
11# Point to the peak
12ax.annotate('Local Maximum', xy=(2, 1), xytext=(3, 1.5),
13 arrowprops=dict(facecolor='black', shrink=0.05))
14 
15ax.set_ylim(-2, 2)
16plt.show()
17 

Complex Layouts with GridSpec

While plt.subplots() handles simple grids, GridSpec allows for plots that span multiple rows or columns.

python
1 
2import matplotlib.pyplot as plt
3 
4fig = plt.figure(figsize=(8, 6))
5gs = fig.add_gridspec(3, 3)
6 
7ax1 = fig.add_subplot(gs[0, :])
8ax1.set_title('Top row, full width')
9 
10ax2 = fig.add_subplot(gs[1:, :2])
11ax2.set_title('Bottom left, big')
12 
13ax3 = fig.add_subplot(gs[1, 2])
14ax3.set_title('Small 1')
15 
16ax4 = fig.add_subplot(gs[2, 2])
17ax4.set_title('Small 2')
18 
19plt.tight_layout()
20plt.show()
21 

In the next lesson, we will see how Seaborn makes these complex statistical visualizations much easier to achieve.