Matplotlib

A complete Matplotlib cheatsheet

Setup & Basics

TaskCodeDescription
Import Matplotlibimport matplotlib.pyplot as pltImport pyplot module
Inline plotting (Jupyter)%matplotlib inlineDisplay plots inline
Basic plotplt.plot([1,2,3],[4,5,6])Simple line plot
Show plotplt.show()Display figure
Create figureplt.figure(figsize=(6,4))Create custom figure
Clear figureplt.clf()Clear figure
Save figureplt.savefig('plot.png')Save plot as image
Close figureplt.close()Close figure window

Line Plot

TaskCodeDescription
Simple lineplt.plot(x, y)Basic line chart
Line colorplt.plot(x, y, color='red')Change line color
Line styleplt.plot(x, y, linestyle='--')Dashed line
Line widthplt.plot(x, y, linewidth=2)Set line thickness
Marker styleplt.plot(x, y, marker='o')Show data points
Marker sizeplt.plot(x, y, marker='s', markersize=8)Change marker size
Multiple linesplt.plot(x, y1); plt.plot(x, y2)Multiple plots
Label lineplt.plot(x, y, label='Sales')Add label
Show legendplt.legend()Display legend box

Labels & Titles

TaskCodeDescription
X-axis labelplt.xlabel('X Axis')Add X label
Y-axis labelplt.ylabel('Y Axis')Add Y label
Titleplt.title('My Graph')Add graph title
Add gridplt.grid(True)Show grid lines
Set axis limitsplt.xlim(0,10) / plt.ylim(0,100)Define value range
Add textplt.text(2, 50, 'Peak')Place text inside plot
Annotateplt.annotate('Point', xy=(2,3), xytext=(3,5), arrowprops=dict(arrowstyle='->'))Add arrow annotation

Bar Chart

TaskCodeDescription
Vertical barsplt.bar(x, y)Basic bar chart
Horizontal barsplt.barh(x, y)Horizontal bars
Bar colorplt.bar(x, y, color='green')Change bar color
Bar widthplt.bar(x, y, width=0.4)Adjust bar width
Add labelsplt.xlabel('Items'); plt.ylabel('Quantity')Axis labels
Add valuesplt.text(i, v, str(v))Add numbers on bars
Multiple barsplt.bar(x-0.2, y1, width=0.4); plt.bar(x+0.2, y2, width=0.4)Grouped bars

Pie Chart

TaskCodeDescription
Basic pieplt.pie(values)Simple pie chart
Add labelsplt.pie(values, labels=labels)Label each slice
Show percentagesplt.pie(values, labels=labels, autopct='%1.1f%%')Display percentage
Explode sliceplt.pie(values, explode=[0,0.1,0,0])Offset one slice
Start angleplt.pie(values, startangle=90)Rotate start point
Equal aspectplt.axis('equal')Make pie circular

Scatter Plot

TaskCodeDescription
Basic scatterplt.scatter(x, y)Simple scatter plot
Marker sizeplt.scatter(x, y, s=50)Control dot size
Marker colorplt.scatter(x, y, c='red')Set color
Vary colorsplt.scatter(x, y, c=values, cmap='viridis')Gradient colors
Transparencyplt.scatter(x, y, alpha=0.5)Semi-transparent dots
Add color barplt.colorbar()Add color scale

Histogram

TaskCodeDescription
Basic histogramplt.hist(data)Plot frequency distribution
Binsplt.hist(data, bins=10)Number of bins
Colorplt.hist(data, color='orange')Set color
Edge colorplt.hist(data, edgecolor='black')Add edges
Transparencyplt.hist(data, alpha=0.7)Adjust opacity
Orientationplt.hist(data, orientation='horizontal')Horizontal bars

Subplots

TaskCodeDescription
Create subplotplt.subplot(2,2,1)2x2 grid, first plot
Adjust layoutplt.tight_layout()Prevent overlap
Figure + axesfig, ax = plt.subplots()Create figure/axes object
Multiple axesfig, (ax1, ax2) = plt.subplots(1,2)Side-by-side plots
Plot on axisax.plot(x, y)Plot using object-oriented style
Set titleax.set_title('Line Chart')Add title to subplot

Colors, Styles, & Themes

TaskCodeDescription
Change styleplt.style.use('ggplot')Apply theme
Available stylesplt.style.availableShow all styles
Set colorcolor='r' or '#FF5733'RGB or hex
Line stylelinestyle='--' or ':'Custom dash
Marker typemarker='o' or 's'Shape of points
Alpha transparencyalpha=0.6Opacity level

Axes Customization

TaskCodeDescription
Set ticksplt.xticks([1,2,3])Custom x ticks
Tick labelsplt.xticks([1,2], ['A','B'])Rename ticks
Rotate ticksplt.xticks(rotation=45)Rotate labels
Add legendplt.legend(loc='upper left')Legend position
Change backgroundax.set_facecolor('#EFEFEF')Background color
Add borderplt.box(True)Toggle border box

3D Plot (Optional)

TaskCodeDescription
Import 3D Axesfrom mpl_toolkits.mplot3d import Axes3D3D setup
Create figurefig = plt.figure()New figure
Add 3D plotax = fig.add_subplot(111, projection='3d')Add 3D subplot
3D scatterax.scatter(x, y, z)3D scatter plot
3D lineax.plot3D(x, y, z)3D line plot
3D surfaceax.plot_surface(X, Y, Z, cmap='viridis')Surface plot

Save & Export

TaskCodeDescription
Save PNGplt.savefig('chart.png')Save as image
Save high qualityplt.savefig('chart.png', dpi=300)High resolution
Save PDFplt.savefig('plot.pdf')Export as PDF
Transparent backgroundplt.savefig('chart.png', transparent=True)Transparent plot