+10 XP

Building Your First Plot

The anatomy of a matplotlib plot:

python
import matplotlib.pyplot as plt
# Step 1: Create figure and axes
Create figure (window) and axes (plotting area). figsize controls dimensions in inches
fig, ax = plt.subplots(figsize=(8, 5))
# Step 2: Plot data (ax.plot, ax.scatter, ax.hist, etc.)
Plot first dataset: (x=[1,2,3], y=[10,20,15]) with circles+line, blue, labeled 'Neuron A'
ax.plot([1, 2, 3], [10, 20, 15], 'o-', color='blue', linewidth=2, label='Neuron A')
Plot second dataset: (x=[1,2,3], y=[12,18,19]) with squares+line, red, labeled 'Neuron B'
ax.plot([1, 2, 3], [12, 18, 19], 's-', color='red', linewidth=2, label='Neuron B')
# Step 3: Labels and titles
Set x-axis label with font size 12 points
ax.set_xlabel('Time (ms)', fontsize=12)
Set y-axis label with font size 12 points
ax.set_ylabel('Firing Rate (Hz)', fontsize=12)
Set plot title (appears at top) with font size 14 points
ax.set_title('Two Neurons Responding to the Same Stimulus', fontsize=14)
# Step 4: Legend and cleanup
Show legend: displays which line is which neuron. loc='best' finds the best position
ax.legend(loc='best')
Add grid lines to make reading values easier. alpha=0.3 makes them semi-transparent
ax.grid(True, alpha=0.3)
Automatically adjust spacing so labels don't get cut off
plt.tight_layout()
Display the finished plot
plt.show()

💡 This is the PROFESSIONAL structure. fig/ax style (instead of plt.plot directly) scales to complex multi-panel figures. ALL NMA code uses this pattern.

Plot types you'll use in NMA:
plot() — line plots (voltage vs time)
scatter() — spike raster (when did neurons fire?)
hist() — distribution (how many spikes at each time?)
imshow() — heatmaps (population firing rates across time)
errorbar() — mean ± std (uncertainty in measurements)

Every plot needs: x-label, y-label, title, and legend (if multiple lines). Missing these = instant feedback from NMA instructors. These three lines keep you safe:
ax.set_xlabel(...)
ax.set_ylabel(...)
ax.set_title(...)