Vai al contenuto
__HTML_TAG_132_📄 Generare Matplotlib PDF Guida_HTML_TAG_133__

Matplotlib Cheatsheet

Installazione

Tabella_136_

Comandi di base

Tabella_137_

Personalizzazione della trama

Tabella_138_

Uso avanzato

Tabella_139_

3D Plotting

TABELLA: 140_

Interfaccia orientata agli oggetti

Tabella_141_

Configurazione

Configurazione runtime (rcParams)

import matplotlib.pyplot as plt

# Set default figure size
plt.rcParams['figure.figsize'] = (10, 6)

# Set default DPI
plt.rcParams['figure.dpi'] = 100

# Set default font size
plt.rcParams['font.size'] = 12

# Set default line width
plt.rcParams['lines.linewidth'] = 2

# Set default colormap
plt.rcParams['image.cmap'] = 'viridis'

# Use LaTeX for text rendering
plt.rcParams['text.usetex'] = True

# Set backend
plt.rcParams['backend'] = 'TkAgg'

Style Sheets

# Use built-in style
plt.style.use('seaborn-v0_8')
plt.style.use('ggplot')
plt.style.use('dark_background')

# List available styles
print(plt.style.available)

# Use multiple styles (later ones override earlier)
plt.style.use(['seaborn-v0_8', 'seaborn-v0_8-poster'])

# Temporary style context
with plt.style.context('dark_background'):
    plt.plot(x, y)

Configuration File (matplotlibrc)

Crea ~/.config/matplotlib/matplotlibrc (Linux/macOS) o __INLINE_CODE_98_ (Windows):

# Figure properties
figure.figsize: 10, 6
figure.dpi: 100

# Font properties
font.size: 12
font.family: sans-serif

# Line properties
lines.linewidth: 2
lines.markersize: 8

# Grid properties
grid.alpha: 0.3
grid.linestyle: --

# Legend properties
legend.frameon: False
legend.loc: best

# Axes properties
axes.grid: True
axes.titlesize: 14
axes.labelsize: 12

Common Use Cases

Use Case 1: Piazzole di linea multiple con la leggenda

import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.exp(-x/10)

# Create plot
plt.figure(figsize=(10, 6))
plt.plot(x, y1, 'b-', label='sin(x)', linewidth=2)
plt.plot(x, y2, 'r--', label='cos(x)', linewidth=2)
plt.plot(x, y3, 'g-.', label='damped sin(x)', linewidth=2)

# Customize
plt.xlabel('X axis', fontsize=12)
plt.ylabel('Y axis', fontsize=12)
plt.title('Trigonometric Functions', fontsize=14)
plt.legend(loc='upper right')
plt.grid(True, alpha=0.3)

# Save and display
plt.savefig('trig_functions.png', dpi=300, bbox_inches='tight')
plt.show()

Use Case 2: Subplots with Different Plot Types

import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 50)
y = 2 * x + 1 + np.random.randn(50) * 2
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]

# Create 2x2 subplot grid
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

# Scatter plot
axes[0, 0].scatter(x, y, alpha=0.6)
axes[0, 0].set_title('Scatter Plot')
axes[0, 0].set_xlabel('X')
axes[0, 0].set_ylabel('Y')

# Line plot
axes[0, 1].plot(x, np.sin(x), 'r-', linewidth=2)
axes[0, 1].set_title('Line Plot')
axes[0, 1].grid(True)

# Bar chart
axes[1, 0].bar(categories, values, color='skyblue', edgecolor='black')
axes[1, 0].set_title('Bar Chart')
axes[1, 0].set_ylabel('Values')

# Histogram
axes[1, 1].hist(y, bins=15, color='green', alpha=0.7, edgecolor='black')
axes[1, 1].set_title('Histogram')
axes[1, 1].set_xlabel('Value')

# Adjust layout and save
plt.tight_layout()
plt.savefig('subplots_example.png', dpi=300)
plt.show()

Use Case 3: Heatmap with Colorbar

import matplotlib.pyplot as plt
import numpy as np

# Generate 2D data
data = np.random.randn(10, 10)

# Create heatmap
fig, ax = plt.subplots(figsize=(8, 6))
im = ax.imshow(data, cmap='RdYlBu_r', aspect='auto')

# Add colorbar
cbar = plt.colorbar(im, ax=ax)
cbar.set_label('Values', rotation=270, labelpad=20)

# Customize ticks
ax.set_xticks(np.arange(10))
ax.set_yticks(np.arange(10))
ax.set_xticklabels([f'Col {i}' for i in range(10)])
ax.set_yticklabels([f'Row {i}' for i in range(10)])

# Rotate x-axis labels
plt.setp(ax.get_xticklabels(), rotation=45, ha='right')

# Add title
ax.set_title('Heatmap Example')

plt.tight_layout()
plt.savefig('heatmap.png', dpi=300, bbox_inches='tight')
plt.show()

Use Case 4: Time Series with Dual Y-Axes

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Generate time series data
dates = pd.date_range('2023-01-01', periods=100)
temperature = 20 + 10 * np.sin(np.linspace(0, 4*np.pi, 100)) + np.random.randn(100)
humidity = 60 + 20 * np.cos(np.linspace(0, 4*np.pi, 100)) + np.random.randn(100) * 5

# Create figure with primary axis
fig, ax1 = plt.subplots(figsize=(12, 6))

# Plot temperature on primary y-axis
color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Temperature (°C)', color=color)
ax1.plot(dates, temperature, color=color, linewidth=2, label='Temperature')
ax1.tick_params(axis='y', labelcolor=color)

# Create secondary y-axis
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Humidity (%)', color=color)
ax2.plot(dates, humidity, color=color, linewidth=2, linestyle='--', label='Humidity')
ax2.tick_params(axis='y', labelcolor=color)

# Add title and grid
plt.title('Temperature and Humidity Over Time')
ax1.grid(True, alpha=0.3)

# Format x-axis dates
fig.autofmt_xdate()

plt.tight_layout()
plt.savefig('dual_axis_timeseries.png', dpi=300)
plt.show()

Use Case 5: Visualizzazione statistica con barre di errore

import matplotlib.pyplot as plt
import numpy as np

# Generate data with error
x = np.arange(0, 10, 1)
y = 2 * x + 5
error = np.random.uniform(0.5, 2.0, len(x))

# Create error bar plot
fig, ax = plt.subplots(figsize=(10, 6))
ax.errorbar(x, y, yerr=error, fmt='o-', capsize=5, capthick=2, 
            ecolor='red', linewidth=2, markersize=8, 
            label='Measured Data')

# Add fitted line
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
ax.plot(x, p(x), 'g--', linewidth=2, label='Fitted Line')

# Customize
ax.set_xlabel('X Variable', fontsize=12)
ax.set_ylabel('Y Variable', fontsize=12)
ax.set_title('Measurements with Error Bars', fontsize=14)
ax.legend()
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig('error_bars.png', dpi=300)
plt.show()

Migliori Pratiche

  • Utilizza l'interfaccia orientata agli oggetti: Per i lotti complessi, utilizzare fig, ax = plt.subplots()_ invece di macchina di stato piplot per un migliore controllo e chiarezza
  • Close Figures: Chiama plt.close() dopo aver salvato le trame in script per liberare la memoria, soprattutto quando si generano molti trame
  • Set Figure Size Early: Definire figsize quando si creano figure per garantire un layout adeguato prima di aggiungere elementi
  • Utilizzare i formati vettoriali: Salvare i dati di pubblicazione in formato PDF o SVG (INLINE_CODE_102_) per scalabilità e qualità
  • Leverage Style Sheets: Usa plt.style.use() per uno styling coerente su più trame invece di impostare i parametri singolarmente
  • Label Everything: Includi sempre le etichette degli assi, i titoli e le leggende per rendere i grafici auto-esplicativi
  • **Utilizza layout **: Chiama plt.tight_layout() o bbox_inches='tight' quando salvi il cutoff dell'etichetta
  • Choose Appropriate Colormaps: Utilizzare colormap percettualmente uniformi come 'viridis', 'plasma', o 'cividis' per i dati scientifici
  • Optimize DPI: Usa dpi=300 per la qualità della stampa, dpi=100 per la visualizzazione dello schermo per bilanciare la qualità e la dimensione del file
  • Elaborazione di stampi. Quando si creano più trame, avvolgere in funzioni e utilizzare i gestori di contesto per garantire una corretta pulizia delle risorse

Risoluzione dei problemi

Issue Solution
Plot doesn't display Call INLINE_CODE_108 at the end, or check if running in non-interactive environment. Use INLINE_CODE_109 for interactive mode
"Matplotlib is currently using agg" backend error Install GUI backend: INLINE_CODE_110 or set backend: INLINE_CODE_111
Labels cut off when saving Use INLINE_CODE_112 before saving or INLINE_CODE_113
Memory leak in loop Call INLINE_CODE_114 or INLINE_CODE_115 after each plot to free memory
Import error on macOS Reinstall with framework build: INLINE_CODE_116 or use conda
Blurry plots Increase DPI: INLINE_CODE_117 or set INLINE_CODE_118
Unicode/LaTeX errors Disable LaTeX: INLINE_CODE_119 or install LaTeX distribution
Slow rendering Reduce data points, use INLINE_CODE_120 for large scatter plots, or switch backend
Legend overlaps data Use INLINE_CODE_121 for auto-positioning or INLINE_CODE_122 for manual placement
Subplot spacing issues Use INLINE_CODE_123 or manually adjust with INLINE_CODE_124
Color not changing Check if using correct parameter name: INLINE_CODE_125 or INLINE_CODE_126, ensure color string is valid
3D plot non funzionante Toolkit Import: from mpl_toolkits.mplot3d import Axes3D e utilizzare projection='3d'