Fundamentals 15 min read

Master Matplotlib: 40+ Python Plotting Techniques from Basics to Advanced

This comprehensive guide walks you through importing Matplotlib, creating basic charts like line, scatter, and histograms, customizing plot elements, legends, color maps, arranging subplots, generating 3D visualizations, and applying these techniques to a Pokémon dataset, all with ready-to-use code snippets for Python developers.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Matplotlib: 40+ Python Plotting Techniques from Basics to Advanced

1. Import

Import the Matplotlib library using the conventional alias:

import matplotlib.pyplot as plt

2. Basic Charts

Examples include plotting a sine curve, line with markers, scatter plot, pie‑style area chart, error bars, bar charts, horizontal bars, histograms, stacked histograms, and 2‑D histograms.

x = np.linspace(0, 10, 30)
plt.plot(x, np.sin(x))
plt.plot(x, np.sin(x), '-o')
plt.scatter(x, np.sin(x))
plt.errorbar(x, y, yerr=dy, fmt='.k')
plt.bar(x, y, tick_label=label)
plt.barh(x, y, tick_label=label)
plt.hist(data)
plt.hist(data, bins=30, histtype='stepfilled', density=True)
plt.hist2d(x, y, bins=30)

3. Custom Plot Elements

Set line style, axis limits, labels, titles, grids, reference lines, shaded regions, annotations, and text.

plt.plot(x, np.sin(x), '--')
plt.ylim(-1.5, 1.5)
plt.xlabel('variable x')
plt.ylabel('value y')
plt.title('三角函数')
plt.grid()
plt.axhline(y=0.8, ls='--', c='r')
plt.axvspan(4, 6, facecolor='r', alpha=0.3)
plt.axhspan(-0.2, 0.2, facecolor='y', alpha=0.3)
plt.text(3.2, 0, 'sin(x)', weight='bold', color='r')
plt.annotate('maximum', xy=(np.pi/2, 1), xytext=(np.pi/2+1, 1), weight='bold', color='r', arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r'))

4. Custom Legends

Create legends, position them, split into columns, and display selective entries.

ax.legend()
ax.legend(loc='upper left', frameon=False)
ax.legend(loc='lower center', ncol=2, frameon=False)
ax.legend(lines[:2], ['first', 'second'])

5. Color Maps

Show color bars, change colormaps, and create discrete color levels.

plt.imshow(I)
plt.colorbar()
plt.imshow(I, cmap='gray')
plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 6))
plt.clim(-1, 1)

6. Multiple Subplots

Define subplot positions, share axes, create grids of subplots, and adjust layout.

ax1 = plt.axes()
ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))
for i in range(1, 7):
    plt.subplot(2, 3, i)
    plt.text(0.5, 0.5, str((2, 3, i)), fontsize=18, ha='center')
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')

7. 3‑D Plots

Create a 3‑D canvas and plot a helix or scatter points.

from mpl_toolkits import mplot3d
fig = plt.figure()
ax = plt.axes(projection='3d')
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline)
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens')

8. Pokémon Dataset Visualizations

Various charts (stacked bar, grouped bar, stacked area, shared‑axis line plots, multi‑line plots, scatter with color encoding, histograms, pie chart, bar chart, correlation heatmap) illustrate Pokémon attributes such as HP, Attack, Defense, Type, and overall scores.

# Example stacked bar
plt.bar(ind, defense, bottom=attack+hp, label='Defense')
plt.bar(ind, attack, bottom=hp, label='Attack')
plt.bar(ind, hp, label='HP')
# Grouped bar
plt.bar(ind, pokemon_hp, width, label='HP')
plt.bar(ind + width, pokemon_attack, width, label='Attack')
# Scatter with color
plt.scatter(x, y, c=colors, alpha=0.5)
# Correlation heatmap
import seaborn as sns
sns.heatmap(corr, annot=True)
Matplotlib example
Matplotlib example
Python visualization library ranking
Python visualization library ranking
GridSpec subplot layout
GridSpec subplot layout
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonMatplotlibSeabornplotting
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.