Matplotlib API Reference
This document provides a quick reference for the most commonly used matplotlib classes and methods.
Core Classes
Figure
The top-level container for all plot elements.
Creation:
fig = plt.figure(figsize=(10, 6), dpi=100, facecolor='white')
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
Key Methods:
fig.add_subplot(nrows, ncols, index) - Add a subplot
fig.add_axes([left, bottom, width, height]) - Add axes at specific position
fig.savefig(filename, dpi=300, bbox_inches='tight') - Save figure
fig.tight_layout() - Adjust spacing to prevent overlaps
fig.suptitle(title) - Set figure title
fig.legend() - Create figure-level legend
fig.colorbar(mappable) - Add colorbar to figure
plt.close(fig) - Close figure to free memory
Key Attributes:
fig.axes - List of all axes in the figure
fig.dpi - Resolution in dots per inch
fig.figsize - Figure dimensions in inches (width, height)
Axes
The actual plotting area where data is visualized.
Creation:
fig, ax = plt.subplots() # Single axes
ax = fig.add_subplot(111) # Alternative method
Plotting Methods:
Line plots:
ax.plot(x, y, **kwargs) - Line plot
ax.step(x, y, where='pre'/'mid'/'post') - Step plot
ax.errorbar(x, y, yerr, xerr) - Error bars
Scatter plots:
ax.scatter(x, y, s=size, c=color, marker='o', alpha=0.5) - Scatter plot
Bar charts:
ax.bar(x, height, width=0.8, align='center') - Vertical bar chart
ax.barh(y, width) - Horizontal bar chart
Statistical plots:
ax.hist(data, bins=10, density=False) - Histogram
ax.boxplot(data, labels=None) - Box plot
ax.violinplot(data) - Violin plot
2D plots:
ax.imshow(array, cmap='viridis', aspect='auto') - Display image/matrix
ax.contour(X, Y, Z, levels=10) - Contour lines
ax.contourf(X, Y, Z, levels=10) - Filled contours
ax.pcolormesh(X, Y, Z) - Pseudocolor plot
Filling:
ax.fill_between(x, y1, y2, alpha=0.3) - Fill between curves
ax.fill_betweenx(y, x1, x2) - Fill between vertical curves
Text and annotations:
ax.text(x, y, text, fontsize=12) - Add text
ax.annotate(text, xy=(x, y), xytext=(x2, y2), arrowprops={}) - Annotate with arrow
Customization Methods:
Labels and titles:
ax.set_xlabel(label, fontsize=12) - Set x-axis label
ax.set_ylabel(label, fontsize=12) - Set y-axis label
ax.set_title(title, fontsize=14) - Set axes title
Limits and scales:
ax.set_xlim(left, right) - Set x-axis limits
ax.set_ylim(bottom, top) - Set y-axis limits
ax.set_xscale('linear'/'log'/'symlog') - Set x-axis scale
ax.set_yscale('linear'/'log'/'symlog') - Set y-axis scale
Ticks:
ax.set_xticks(positions) - Set x-tick positions
ax.set_xticklabels(labels) - Set x-tick labels
ax.tick_params(axis='both', labelsize=10) - Customize tick appearance
Grid and spines:
ax.grid(True, alpha=0.3, linestyle='--') - Add grid
ax.spines['top'].set_visible(False) - Hide top spine
ax.spines['right'].set_visible(False) - Hide right spine
Legend:
ax.legend(loc='best', fontsize=10, frameon=True) - Add legend
ax.legend(handles, labels) - Custom legend
Aspect and layout:
ax.set_aspect('equal'/'auto'/ratio) - Set aspect ratio
ax.invert_xaxis() - Invert x-axis
ax.invert_yaxis() - Invert y-axis
pyplot Module
High-level interface for quick plotting.
Figure creation:
plt.figure() - Create new figure
plt.subplots() - Create figure and axes
plt.subplot() - Add subplot to current figure
Plotting (uses current axes):
plt.plot() - Line plot
plt.scatter() - Scatter plot
plt.bar() - Bar chart
plt.hist() - Histogram
- (All axes methods available)
Display and save:
plt.show() - Display figure
plt.savefig() - Save figure
plt.close() - Close figure
Style:
plt.style.use(style_name) - Apply style sheet
plt.style.available - List available styles
State management:
plt.gca() - Get current axes
plt.gcf() - Get current figure
plt.sca(ax) - Set current axes
plt.clf() - Clear current figure
plt.cla() - Clear current axes
Line and Marker Styles
Line Styles
'-' or 'solid' - Solid line
'--' or 'dashed' - Dashed line
'-.' or 'dashdot' - Dash-dot line
':' or 'dotted' - Dotted line
'' or ' ' or 'None' - No line
Marker Styles
'.' - Point marker
'o' - Circle marker
'v', '^', '<', '>' - Triangle markers
's' - Square marker
'p' - Pentagon marker
'*' - Star marker
'h', 'H' - Hexagon markers
'+' - Plus marker
'x' - X marker
'D', 'd' - Diamond markers
Color Specifications
Single character shortcuts:
'b' - Blue
'g' - Green
'r' - Red
'c' - Cyan
'm' - Magenta
'y' - Yellow
'k' - Black
'w' - White
Named colors:
Other formats:
- Hex:
'#FF5733'
- RGB tuple:
(0.1, 0.2, 0.3)
- RGBA tuple:
(0.1, 0.2, 0.3, 0.5)
Common Parameters
Plot Function Parameters
ax.plot(x, y,
color='blue', # Line color
linewidth=2, # Line width
linestyle='--', # Line style
marker='o', # Marker style
markersize=8, # Marker size
markerfacecolor='red', # Marker fill color
markeredgecolor='black',# Marker edge color
markeredgewidth=1, # Marker edge width
alpha=0.7, # Transparency (0-1)
label='data', # Legend label
zorder=2, # Drawing order
rasterized=True # Rasterize for smaller file size
)
Scatter Function Parameters
ax.scatter(x, y,
s=50, # Size (scalar or array)
c='blue', # Color (scalar, array, or sequence)
marker='o', # Marker style
cmap='viridis', # Colormap (if c is numeric)
alpha=0.5, # Transparency
edgecolors='black', # Edge color
linewidths=1, # Edge width
vmin=0, vmax=1, # Color scale limits
label='data' # Legend label
)
Text Parameters
ax.text(x, y, text,
fontsize=12, # Font size
fontweight='normal', # 'normal', 'bold', 'heavy', 'light'
fontstyle='normal', # 'normal', 'italic', 'oblique'
fontfamily='sans-serif',# Font family
color='black', # Text color
alpha=1.0, # Transparency
ha='center', # Horizontal alignment: 'left', 'center', 'right'
va='center', # Vertical alignment: 'top', 'center', 'bottom', 'baseline'
rotation=0, # Rotation angle in degrees
bbox=dict( # Background box
facecolor='white',
edgecolor='black',
boxstyle='round'
)
)
rcParams Configuration
Common rcParams settings for global customization:
# Font settings
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Arial', 'Helvetica']
plt.rcParams['font.size'] = 12
# Figure settings
plt.rcParams['figure.figsize'] = (10, 6)
plt.rcParams['figure.dpi'] = 100
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['savefig.dpi'] = 300
plt.rcParams['savefig.bbox'] = 'tight'
# Axes settings
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['axes.titlesize'] = 16
plt.rcParams['axes.grid'] = True
plt.rcParams['axes.grid.alpha'] = 0.3
# Line settings
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['lines.markersize'] = 8
# Tick settings
plt.rcParams['xtick.labelsize'] = 10
plt.rcParams['ytick.labelsize'] = 10
plt.rcParams['xtick.direction'] = 'in' # 'in', 'out', 'inout'
plt.rcParams['ytick.direction'] = 'in'
# Legend settings
plt.rcParams['legend.fontsize'] = 12
plt.rcParams['legend.frameon'] = True
plt.rcParams['legend.framealpha'] = 0.8
# Grid settings
plt.rcParams['grid.alpha'] = 0.3
plt.rcParams['grid.linestyle'] = '--'
GridSpec for Complex Layouts
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(12, 8))
gs = GridSpec(3, 3, figure=fig, hspace=0.3, wspace=0.3)
# Span multiple cells
ax1 = fig.add_subplot(gs[0, :]) # Top row, all columns
ax2 = fig.add_subplot(gs[1:, 0]) # Bottom two rows, first column
ax3 = fig.add_subplot(gs[1, 1:]) # Middle row, last two columns
ax4 = fig.add_subplot(gs[2, 1]) # Bottom row, middle column
ax5 = fig.add_subplot(gs[2, 2]) # Bottom row, right column
3D Plotting
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot types
ax.plot(x, y, z) # 3D line
ax.scatter(x, y, z) # 3D scatter
ax.plot_surface(X, Y, Z) # 3D surface
ax.plot_wireframe(X, Y, Z) # 3D wireframe
ax.contour(X, Y, Z) # 3D contour
ax.bar3d(x, y, z, dx, dy, dz) # 3D bar
# Customization
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.view_init(elev=30, azim=45) # Set viewing angle
Animation
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
line, = ax.plot([], [])
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return line,
def update(frame):
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x + frame/10)
line.set_data(x, y)
return line,
anim = FuncAnimation(fig, update, init_func=init,
frames=100, interval=50, blit=True)
# Save animation
anim.save('animation.gif', writer='pillow', fps=20)
anim.save('animation.mp4', writer='ffmpeg', fps=20)
Image Operations
# Read and display image
img = plt.imread('image.png')
ax.imshow(img)
# Display matrix as image
ax.imshow(matrix, cmap='viridis', aspect='auto',
interpolation='nearest', origin='lower')
# Colorbar
cbar = plt.colorbar(im, ax=ax)
cbar.set_label('Values')
# Image extent (set coordinates)
ax.imshow(img, extent=[x_min, x_max, y_min, y_max])
Event Handling
# Mouse click event
def on_click(event):
if event.inaxes:
print(f'Clicked at x={event.xdata:.2f}, y={event.ydata:.2f}')
fig.canvas.mpl_connect('button_press_event', on_click)
# Key press event
def on_key(event):
print(f'Key pressed: {event.key}')
fig.canvas.mpl_connect('key_press_event', on_key)
Useful Utilities
# Get current axis limits
xlims = ax.get_xlim()
ylims = ax.get_ylim()
# Set equal aspect ratio
ax.set_aspect('equal', adjustable='box')
# Share axes between subplots
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
# Twin axes (two y-axes)
ax2 = ax1.twinx()
# Remove tick labels
ax.set_xticklabels([])
ax.set_yticklabels([])
# Scientific notation
ax.ticklabel_format(style='scientific', axis='y', scilimits=(0,0))
# Date formatting
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
1---2name: 051-api-reference-988c2aff3description: Matplotlib API Reference4---5# Matplotlib API Reference67This document provides a quick reference for the most commonly used matplotlib classes and methods.89## Core Classes1011### Figure1213The top-level container for all plot elements.1415**Creation:**16```python17fig = plt.figure(figsize=(10, 6), dpi=100, facecolor='white')18fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))19fig, axes = plt.subplots(2, 2, figsize=(12, 10))20```2122**Key Methods:**23- `fig.add_subplot(nrows, ncols, index)` - Add a subplot24- `fig.add_axes([left, bottom, width, height])` - Add axes at specific position25- `fig.savefig(filename, dpi=300, bbox_inches='tight')` - Save figure26- `fig.tight_layout()` - Adjust spacing to prevent overlaps27- `fig.suptitle(title)` - Set figure title28- `fig.legend()` - Create figure-level legend29- `fig.colorbar(mappable)` - Add colorbar to figure30- `plt.close(fig)` - Close figure to free memory3132**Key Attributes:**33- `fig.axes` - List of all axes in the figure34- `fig.dpi` - Resolution in dots per inch35- `fig.figsize` - Figure dimensions in inches (width, height)3637### Axes3839The actual plotting area where data is visualized.4041**Creation:**42```python43fig, ax = plt.subplots() # Single axes44ax = fig.add_subplot(111) # Alternative method45```4647**Plotting Methods:**4849**Line plots:**50- `ax.plot(x, y, **kwargs)` - Line plot51- `ax.step(x, y, where='pre'/'mid'/'post')` - Step plot52- `ax.errorbar(x, y, yerr, xerr)` - Error bars5354**Scatter plots:**55- `ax.scatter(x, y, s=size, c=color, marker='o', alpha=0.5)` - Scatter plot5657**Bar charts:**58- `ax.bar(x, height, width=0.8, align='center')` - Vertical bar chart59- `ax.barh(y, width)` - Horizontal bar chart6061**Statistical plots:**62- `ax.hist(data, bins=10, density=False)` - Histogram63- `ax.boxplot(data, labels=None)` - Box plot64- `ax.violinplot(data)` - Violin plot6566**2D plots:**67- `ax.imshow(array, cmap='viridis', aspect='auto')` - Display image/matrix68- `ax.contour(X, Y, Z, levels=10)` - Contour lines69- `ax.contourf(X, Y, Z, levels=10)` - Filled contours70- `ax.pcolormesh(X, Y, Z)` - Pseudocolor plot7172**Filling:**73- `ax.fill_between(x, y1, y2, alpha=0.3)` - Fill between curves74- `ax.fill_betweenx(y, x1, x2)` - Fill between vertical curves7576**Text and annotations:**77- `ax.text(x, y, text, fontsize=12)` - Add text78- `ax.annotate(text, xy=(x, y), xytext=(x2, y2), arrowprops={})` - Annotate with arrow7980**Customization Methods:**8182**Labels and titles:**83- `ax.set_xlabel(label, fontsize=12)` - Set x-axis label84- `ax.set_ylabel(label, fontsize=12)` - Set y-axis label85- `ax.set_title(title, fontsize=14)` - Set axes title8687**Limits and scales:**88- `ax.set_xlim(left, right)` - Set x-axis limits89- `ax.set_ylim(bottom, top)` - Set y-axis limits90- `ax.set_xscale('linear'/'log'/'symlog')` - Set x-axis scale91- `ax.set_yscale('linear'/'log'/'symlog')` - Set y-axis scale9293**Ticks:**94- `ax.set_xticks(positions)` - Set x-tick positions95- `ax.set_xticklabels(labels)` - Set x-tick labels96- `ax.tick_params(axis='both', labelsize=10)` - Customize tick appearance9798**Grid and spines:**99- `ax.grid(True, alpha=0.3, linestyle='--')` - Add grid100- `ax.spines['top'].set_visible(False)` - Hide top spine101- `ax.spines['right'].set_visible(False)` - Hide right spine102103**Legend:**104- `ax.legend(loc='best', fontsize=10, frameon=True)` - Add legend105- `ax.legend(handles, labels)` - Custom legend106107**Aspect and layout:**108- `ax.set_aspect('equal'/'auto'/ratio)` - Set aspect ratio109- `ax.invert_xaxis()` - Invert x-axis110- `ax.invert_yaxis()` - Invert y-axis111112### pyplot Module113114High-level interface for quick plotting.115116**Figure creation:**117- `plt.figure()` - Create new figure118- `plt.subplots()` - Create figure and axes119- `plt.subplot()` - Add subplot to current figure120121**Plotting (uses current axes):**122- `plt.plot()` - Line plot123- `plt.scatter()` - Scatter plot124- `plt.bar()` - Bar chart125- `plt.hist()` - Histogram126- (All axes methods available)127128**Display and save:**129- `plt.show()` - Display figure130- `plt.savefig()` - Save figure131- `plt.close()` - Close figure132133**Style:**134- `plt.style.use(style_name)` - Apply style sheet135- `plt.style.available` - List available styles136137**State management:**138- `plt.gca()` - Get current axes139- `plt.gcf()` - Get current figure140- `plt.sca(ax)` - Set current axes141- `plt.clf()` - Clear current figure142- `plt.cla()` - Clear current axes143144## Line and Marker Styles145146### Line Styles147- `'-'` or `'solid'` - Solid line148- `'--'` or `'dashed'` - Dashed line149- `'-.'` or `'dashdot'` - Dash-dot line150- `':'` or `'dotted'` - Dotted line151- `''` or `' '` or `'None'` - No line152153### Marker Styles154- `'.'` - Point marker155- `'o'` - Circle marker156- `'v'`, `'^'`, `'<'`, `'>'` - Triangle markers157- `'s'` - Square marker158- `'p'` - Pentagon marker159- `'*'` - Star marker160- `'h'`, `'H'` - Hexagon markers161- `'+'` - Plus marker162- `'x'` - X marker163- `'D'`, `'d'` - Diamond markers164165### Color Specifications166167**Single character shortcuts:**168- `'b'` - Blue169- `'g'` - Green170- `'r'` - Red171- `'c'` - Cyan172- `'m'` - Magenta173- `'y'` - Yellow174- `'k'` - Black175- `'w'` - White176177**Named colors:**178- `'steelblue'`, `'coral'`, `'teal'`, etc.179- See full list: https://matplotlib.org/stable/gallery/color/named_colors.html180181**Other formats:**182- Hex: `'#FF5733'`183- RGB tuple: `(0.1, 0.2, 0.3)`184- RGBA tuple: `(0.1, 0.2, 0.3, 0.5)`185186## Common Parameters187188### Plot Function Parameters189190```python191ax.plot(x, y,192 color='blue', # Line color193 linewidth=2, # Line width194 linestyle='--', # Line style195 marker='o', # Marker style196 markersize=8, # Marker size197 markerfacecolor='red', # Marker fill color198 markeredgecolor='black',# Marker edge color199 markeredgewidth=1, # Marker edge width200 alpha=0.7, # Transparency (0-1)201 label='data', # Legend label202 zorder=2, # Drawing order203 rasterized=True # Rasterize for smaller file size204)205```206207### Scatter Function Parameters208209```python210ax.scatter(x, y,211 s=50, # Size (scalar or array)212 c='blue', # Color (scalar, array, or sequence)213 marker='o', # Marker style214 cmap='viridis', # Colormap (if c is numeric)215 alpha=0.5, # Transparency216 edgecolors='black', # Edge color217 linewidths=1, # Edge width218 vmin=0, vmax=1, # Color scale limits219 label='data' # Legend label220)221```222223### Text Parameters224225```python226ax.text(x, y, text,227 fontsize=12, # Font size228 fontweight='normal', # 'normal', 'bold', 'heavy', 'light'229 fontstyle='normal', # 'normal', 'italic', 'oblique'230 fontfamily='sans-serif',# Font family231 color='black', # Text color232 alpha=1.0, # Transparency233 ha='center', # Horizontal alignment: 'left', 'center', 'right'234 va='center', # Vertical alignment: 'top', 'center', 'bottom', 'baseline'235 rotation=0, # Rotation angle in degrees236 bbox=dict( # Background box237 facecolor='white',238 edgecolor='black',239 boxstyle='round'240 )241)242```243244## rcParams Configuration245246Common rcParams settings for global customization:247248```python249# Font settings250plt.rcParams['font.family'] = 'sans-serif'251plt.rcParams['font.sans-serif'] = ['Arial', 'Helvetica']252plt.rcParams['font.size'] = 12253254# Figure settings255plt.rcParams['figure.figsize'] = (10, 6)256plt.rcParams['figure.dpi'] = 100257plt.rcParams['figure.facecolor'] = 'white'258plt.rcParams['savefig.dpi'] = 300259plt.rcParams['savefig.bbox'] = 'tight'260261# Axes settings262plt.rcParams['axes.labelsize'] = 14263plt.rcParams['axes.titlesize'] = 16264plt.rcParams['axes.grid'] = True265plt.rcParams['axes.grid.alpha'] = 0.3266267# Line settings268plt.rcParams['lines.linewidth'] = 2269plt.rcParams['lines.markersize'] = 8270271# Tick settings272plt.rcParams['xtick.labelsize'] = 10273plt.rcParams['ytick.labelsize'] = 10274plt.rcParams['xtick.direction'] = 'in' # 'in', 'out', 'inout'275plt.rcParams['ytick.direction'] = 'in'276277# Legend settings278plt.rcParams['legend.fontsize'] = 12279plt.rcParams['legend.frameon'] = True280plt.rcParams['legend.framealpha'] = 0.8281282# Grid settings283plt.rcParams['grid.alpha'] = 0.3284plt.rcParams['grid.linestyle'] = '--'285```286287## GridSpec for Complex Layouts288289```python290from matplotlib.gridspec import GridSpec291292fig = plt.figure(figsize=(12, 8))293gs = GridSpec(3, 3, figure=fig, hspace=0.3, wspace=0.3)294295# Span multiple cells296ax1 = fig.add_subplot(gs[0, :]) # Top row, all columns297ax2 = fig.add_subplot(gs[1:, 0]) # Bottom two rows, first column298ax3 = fig.add_subplot(gs[1, 1:]) # Middle row, last two columns299ax4 = fig.add_subplot(gs[2, 1]) # Bottom row, middle column300ax5 = fig.add_subplot(gs[2, 2]) # Bottom row, right column301```302303## 3D Plotting304305```python306from mpl_toolkits.mplot3d import Axes3D307308fig = plt.figure()309ax = fig.add_subplot(111, projection='3d')310311# Plot types312ax.plot(x, y, z) # 3D line313ax.scatter(x, y, z) # 3D scatter314ax.plot_surface(X, Y, Z) # 3D surface315ax.plot_wireframe(X, Y, Z) # 3D wireframe316ax.contour(X, Y, Z) # 3D contour317ax.bar3d(x, y, z, dx, dy, dz) # 3D bar318319# Customization320ax.set_xlabel('X')321ax.set_ylabel('Y')322ax.set_zlabel('Z')323ax.view_init(elev=30, azim=45) # Set viewing angle324```325326## Animation327328```python329from matplotlib.animation import FuncAnimation330331fig, ax = plt.subplots()332line, = ax.plot([], [])333334def init():335 ax.set_xlim(0, 2*np.pi)336 ax.set_ylim(-1, 1)337 return line,338339def update(frame):340 x = np.linspace(0, 2*np.pi, 100)341 y = np.sin(x + frame/10)342 line.set_data(x, y)343 return line,344345anim = FuncAnimation(fig, update, init_func=init,346 frames=100, interval=50, blit=True)347348# Save animation349anim.save('animation.gif', writer='pillow', fps=20)350anim.save('animation.mp4', writer='ffmpeg', fps=20)351```352353## Image Operations354355```python356# Read and display image357img = plt.imread('image.png')358ax.imshow(img)359360# Display matrix as image361ax.imshow(matrix, cmap='viridis', aspect='auto',362 interpolation='nearest', origin='lower')363364# Colorbar365cbar = plt.colorbar(im, ax=ax)366cbar.set_label('Values')367368# Image extent (set coordinates)369ax.imshow(img, extent=[x_min, x_max, y_min, y_max])370```371372## Event Handling373374```python375# Mouse click event376def on_click(event):377 if event.inaxes:378 print(f'Clicked at x={event.xdata:.2f}, y={event.ydata:.2f}')379380fig.canvas.mpl_connect('button_press_event', on_click)381382# Key press event383def on_key(event):384 print(f'Key pressed: {event.key}')385386fig.canvas.mpl_connect('key_press_event', on_key)387```388389## Useful Utilities390391```python392# Get current axis limits393xlims = ax.get_xlim()394ylims = ax.get_ylim()395396# Set equal aspect ratio397ax.set_aspect('equal', adjustable='box')398399# Share axes between subplots400fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)401402# Twin axes (two y-axes)403ax2 = ax1.twinx()404405# Remove tick labels406ax.set_xticklabels([])407ax.set_yticklabels([])408409# Scientific notation410ax.ticklabel_format(style='scientific', axis='y', scilimits=(0,0))411412# Date formatting413import matplotlib.dates as mdates414ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))415ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))416```