_
_
Matplotlib Cheatsheet¶
• Installation
| Platform | Command |
|---|---|
| Ubuntu/Debian | INLINE_CODE_8 or INLINE_CODE_9 |
| RHEL/Fedora | INLINE_CODE_10 or INLINE_CODE_11 |
| macOS | INLINE_CODE_12 or INLINE_CODE_13 |
| Windows | INLINE_CODE_14 |
| Conda (All) | INLINE_CODE_15 |
| Virtual Env | INLINE_CODE_16 |
| With All Features | INLINE_CODE_17 |
| Verify Install | INLINE_CODE_18 |
| _ | |
| oder Grundlegende Befehle |
| Command | Description |
|---|---|
| INLINE_CODE_19 | Import pyplot module (standard convention) |
| INLINE_CODE_20 | Create a basic line plot |
| INLINE_CODE_21 | Create a scatter plot |
| INLINE_CODE_22 | Create a vertical bar chart |
| INLINE_CODE_23 | Create a horizontal bar chart |
| INLINE_CODE_24 | Create a histogram with 30 bins |
| INLINE_CODE_25 | Set x-axis label |
| INLINE_CODE_26 | Set y-axis label |
| INLINE_CODE_27 | Set plot title |
| INLINE_CODE_28 | Display legend for labeled data |
| INLINE_CODE_29 | Add grid lines to plot |
| INLINE_CODE_30 | Set x-axis limits |
| INLINE_CODE_31 | Set y-axis limits |
| INLINE_CODE_32 | Display the plot in a window |
| INLINE_CODE_33 | Save plot to file |
| INLINE_CODE_34 | Close current figure and free memory |
| INLINE_CODE_35 | Create new figure with size in inches |
| INLINE_CODE_36 | Create figure and single axes (OO interface) |
| INLINE_CODE_37 | Create 2x2 grid of subplots |
| INLINE_CODE_38 | Create subplot in 2x2 grid, position 1 |
| _ | |
| Individuelle Anpassung |
| Command | Description |
|---|---|
| INLINE_CODE_39 | Red dashed line (color + linestyle shorthand) |
| INLINE_CODE_40 | Set line width |
| INLINE_CODE_41 | Set color using hex code |
| INLINE_CODE_42 | Add circular markers at data points |
| INLINE_CODE_43 | Set marker size |
| INLINE_CODE_44 | Set transparency (0=transparent, 1=opaque) |
| INLINE_CODE_45 | Add label for legend |
| INLINE_CODE_46 | Scatter with size and color arrays |
| INLINE_CODE_47 | Use colormap for scatter colors |
| INLINE_CODE_48 | Rotate x-axis tick labels 45 degrees |
| INLINE_CODE_49 | Set custom tick positions and labels |
| INLINE_CODE_50 | Customize grid appearance |
| INLINE_CODE_51 | Position legend in specific location |
| INLINE_CODE_52 | Adjust spacing to prevent label overlap |
| INLINE_CODE_53 | Equal aspect ratio for x and y axes |
| _ | |
| / Fortgeschrittene Nutzung |
| Command | Description |
|---|---|
| INLINE_CODE_54 | Plot with error bars |
| INLINE_CODE_55 | Fill area between two curves |
| INLINE_CODE_56 | Create contour plot from 2D data |
| INLINE_CODE_57 | Filled contour plot with 20 levels |
| INLINE_CODE_58 | Display 2D array as image/heatmap |
| INLINE_CODE_59 | Add colorbar to current plot |
| INLINE_CODE_60 | Create box and whisker plot |
| INLINE_CODE_61 | Create violin plot (distribution shape) |
| INLINE_CODE_62 | Pie chart with percentage labels |
| INLINE_CODE_63 | Create second y-axis sharing same x-axis |
| INLINE_CODE_64 | Plot with logarithmic x-axis |
| INLINE_CODE_65 | Plot with logarithmic y-axis |
| INLINE_CODE_66 | Plot with both axes logarithmic |
| INLINE_CODE_67 | Step plot with steps at midpoints |
| INLINE_CODE_68 | Create stem plot (lollipop chart) |
| INLINE_CODE_69 | Hexagonal binning plot |
| INLINE_CODE_70 | Streamlines for vector field |
| INLINE_CODE_71 | Arrow plot for vector field |
| INLINE_CODE_72 | Set x-axis to logarithmic scale (OO) |
| INLINE_CODE_73 | Add annotation at specific point |
| _ | |
| 3D Plotting |
| Command | Description |
|---|---|
| INLINE_CODE_74 | Import 3D plotting toolkit |
| INLINE_CODE_75 | Create 3D axes |
| INLINE_CODE_76 | 3D line plot |
| INLINE_CODE_77 | 3D scatter plot |
| INLINE_CODE_78 | 3D surface plot |
| INLINE_CODE_79 | 3D wireframe plot |
| INLINE_CODE_80 | 3D contour plot |
| INLINE_CODE_81 | Set 3D x-axis label |
| INLINE_CODE_82 | Set 3D viewing angle |
| _ | |
| Objektorientierte Schnittstelle |
| Command | Description |
|---|---|
| INLINE_CODE_83 | Create figure and axes objects |
| INLINE_CODE_84 | Plot using axes object |
| INLINE_CODE_85 | Set x-axis label (OO method) |
| INLINE_CODE_86 | Set y-axis label (OO method) |
| INLINE_CODE_87 | Set title (OO method) |
| INLINE_CODE_88 | Set x-axis limits (OO method) |
| INLINE_CODE_89 | Set y-axis limits (OO method) |
| INLINE_CODE_90 | Add legend (OO method) |
| INLINE_CODE_91 | Enable grid (OO method) |
| INLINE_CODE_92 | Set aspect ratio |
| INLINE_CODE_93 | Set overall figure title |
| INLINE_CODE_94 | Adjust subplot spacing |
| INLINE_CODE_95 | Hide top spine/border |
| INLINE_CODE_96 | Customize tick parameters |
| _ | |
| Konfiguration |
Runtime Configuration (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)
Konfigurationsdatei (matplotlibrc)¶
Erstellen ~/.config/matplotlib/matplotlibrc (Linux/macOS) oder %USERPROFILE%\.matplotlib\matplotlibrc (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
Häufige Anwendungsfälle
Use Case 1: Multiple Line Plots mit Legende¶
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 mit verschiedenen Plottypen¶
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 mit 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 mit 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: Statistische Visualisierung mit Fehlern¶
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()
oder Best Practices
- **Use Object-Oriented Interface*: Für komplexe Handlungen verwenden Sie __INLINE_CODE_99_ anstelle von Pyplot-Zustandsmaschine für bessere Kontrolle und Klarheit
- **Close Figures*: Call __INLINE_CODE_100_ nach dem Speichern von Plots in Skripten zum freien Speicher, vor allem bei der Generierung vieler Plots
- Set Abbildungsgröße Früh: Define
figsizebei der Erstellung von Zahlen, um ein korrektes Layout vor dem Hinzufügen von Elementen sicherzustellen - **Verwendete Vectorized Formate*: Publikationszahlen als PDF oder SVG (
plt.savefig('plot.pdf')) für Skalierbarkeit und Qualität speichern - **Leverage Style Sheets*: Verwenden Sie
plt.style.use()zur konsequenten Styling über mehrere Parzellen statt Parameter individuell einzustellen - **Label Everything*: Immer Achsetiketten, Titel und Legenden enthalten, um Grundstücke selbsterklärend zu machen
- **Use Tight Layout*: Call
plt.tight_layout()oderbbox_inches='tight'beim Speichern von Etikettenabschaltungen - **Wählen Sie entsprechende Farbkarten*: Verwendung perzeptuell einheitlicher Farbkarten wie 'viridis', 'plasma' oder 'cividis' für wissenschaftliche Daten
- Optimize DPI: Verwenden Sie
dpi=300für Druckqualitätdpi=100für Bildschirmanzeige zur Balance von Qualität und Dateigröße - **Batch Processing*: Wenn Sie mehrere Parzellen erstellen, Funktionen einpacken und Kontextmanager verwenden, um eine ordnungsgemäße Ressourcenreinigung zu gewährleisten
Fehlerbehebung
| 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 funktioniert nicht | Import Toolkit: from mpl_toolkits.mplot3d import Axes3D und verwenden projection='3d' |