Matplotlib is a popular Python library for creating static, interactive, and animated visualizations in a variety of formats. Below is a Matplotlib cheat sheet covering common plotting techniques and customization options:
Basic Plotting
Line Plot:
import matplotlib.pyplot as plt
plt.plot(x, y, label='label')
plt.xlabel('x-axis label')
plt.ylabel('y-axis label')
plt.title('Title')
plt.legend()
plt.show()
Scatter Plot:
plt.scatter(x, y, label='label', marker='o')
Bar Plot:
plt.bar(x, height, width=0.8, align='center', label='label')
Histogram:
plt.hist(data, bins=10, edgecolor='black')
Customization
Colors and Markers:
plt.plot(x, y, color='blue', linestyle='--', marker='o', markersize=8, label='label')
Title and Labels:
plt.title('Title', fontsize=16)
plt.xlabel('x-axis label', fontsize=12)
plt.ylabel('y-axis label', fontsize=12)
Legend:
plt.legend(loc='upper right', fontsize=10)
Grid:
plt.grid(True, linestyle='--', alpha=0.5)
Axis Limits:
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
Subplots
Subplots:
plt.subplot(rows, cols, index)
Multiple Plots:
plt.subplot(2, 1, 1)
plt.plot(x1, y1)
plt.subplot(2, 1, 2)
plt.plot(x2, y2)
Annotations and Text
Text Annotation:
plt.annotate('text', xy=(x, y), xytext=(x_text, y_text), arrowprops=dict(facecolor='black', shrink=0.05))
Text:
plt.text(x, y, 'text', fontsize=12, ha='center', va='center')
Save and Show
Save Figure:
plt.savefig('figure.png', dpi=300, bbox_inches='tight')
Show Plot:
plt.show()
Advanced Plots
Heatmap:
import seaborn as sns
sns.heatmap(data, cmap='viridis', annot=True)
3D Plot:
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='r', marker='o')
Pie Chart:
labels = ['Label1', 'Label2', 'Label3']
sizes = [25, 40, 35]
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=['red', 'green', 'blue'])
This cheat sheet provides a quick reference for common Matplotlib plotting techniques. For more detailed information and customization options, refer to the official Matplotlib documentation. Additionally, you can explore the Seaborn library for more advanced visualizations built on top of Matplotlib.