logo
📊 数据科学

Matplotlib

Matplotlib Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · 数据科学🧭 Markdown 速查🏷️ 2 个标签
#matplotlib#visualization
向下滚动查看内容
返回全部 Cheat Sheets

Getting Started

Importing
PYTHON
滚动查看更多
import matplotlib.pyplot as plt  # Core plotting library
import numpy as np               # For numerical operations
Basic Plot
PYTHON
滚动查看更多
x = np.linspace(0, 10, 100)      # 100 points between 0 and 10
y = np.sin(x)                    # Sine function values
plt.plot(x, y)                   # Create a line plot
plt.show()                       # Display the plot

Plot Types

Line Plot
PYTHON
滚动查看更多
plt.plot(x, y)                   # Line plot of y vs x
plt.title("Sine Wave")          # Set title
plt.xlabel("x-axis")            # Label x-axis
plt.ylabel("y-axis")            # Label y-axis
plt.grid(True)                  # Show gridlines
plt.show()
Scatter Plot
PYTHON
滚动查看更多
plt.scatter(x, y)               # Scatter plot
plt.title("Scatter Plot")
plt.show()
Bar Plot
PYTHON
滚动查看更多
categories = ['A', 'B', 'C']
values = [10, 20, 15]
plt.bar(categories, values)     # Vertical bar chart
plt.title("Bar Chart")
plt.show()
Horizontal Bar Plot
PYTHON
滚动查看更多
plt.barh(categories, values)    # Horizontal bar chart
plt.title("Horizontal Bar Chart")
plt.show()
Histogram
PYTHON
滚动查看更多
data = np.random.randn(1000)    # Random normal distribution
plt.hist(data, bins=30)         # Histogram with 30 bins
plt.title("Histogram")
plt.show()
Pie Chart
PYTHON
滚动查看更多
sizes = [25, 35, 20, 20]
labels = ['A', 'B', 'C', 'D']
plt.pie(sizes, labels=labels, autopct='%1.1f%%')  # Pie chart with % labels
plt.title("Pie Chart")
plt.show()

Customization

FeatureCode ExampleDescription
Titleplt.title("Title")Set the title of the plot
X/Y Labelsplt.xlabel("X"), plt.ylabel("Y")Label the axes
Gridplt.grid(True)Show grid
Legendplt.legend(["line1"])Add legend
Line Styleplt.plot(x, y, linestyle='--')Dashed line
Colorplt.plot(x, y, color='green')Set line color
Markerplt.plot(x, y, marker='o')Show markers on points
Axis Limitsplt.xlim(0, 10), plt.ylim(-1, 1)Set axis range
Tick Labelsplt.xticks([...]), plt.yticks([...])Customize tick positions
Text Annotationplt.text(5, 0, "Midpoint")Add text at a specific coordinate
Arrowplt.annotate("Peak", xy=(7, 1), xytext=(6, 1.5), arrowprops=dict(arrowstyle="->"))Add annotation arrow
Style Sheetsplt.style.use('ggplot')Use predefined styles like seaborn, bmh

Subplots & Layouts

Multiple Subplots
PYTHON
滚动查看更多
fig, axs = plt.subplots(2, 2)        # Create 2x2 grid of subplots
axs[0, 0].plot(x, y)                 # Top-left subplot
axs[0, 1].scatter(x, y)              # Top-right subplot
axs[1, 0].bar(categories, values)    # Bottom-left subplot
axs[1, 1].hist(data)                 # Bottom-right subplot
plt.tight_layout()                   # Adjust spacing to prevent overlap
plt.show()
Figure Size
PYTHON
滚动查看更多
plt.figure(figsize=(10, 5))         # Set figure size (width, height in inches)

Advanced Visualizations

Heatmap
PYTHON
滚动查看更多
data = np.random.rand(10, 10)       # Random 10x10 matrix
plt.imshow(data, cmap='hot', interpolation='nearest')  # Display as image
plt.colorbar()                      # Show color scale
plt.title("Heatmap")
plt.show()
Contour Plot
PYTHON
滚动查看更多
X, Y = np.meshgrid(x, x)
Z = np.sin(X) * np.cos(Y)
plt.contour(X, Y, Z)                # Contour lines
plt.title("Contour Plot")
plt.show()
3D Plot
PYTHON
滚动查看更多
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')  # 3D subplot
ax.plot3D(x, y, np.cos(x))                  # 3D line
plt.title("3D Plot")
plt.show()

Working with Images

PYTHON
滚动查看更多
import matplotlib.image as mpimg
img = mpimg.imread('image.jpg')     # Load image
plt.imshow(img)                     # Display image
plt.axis('off')                     # Hide axes
plt.title("Image Display")
plt.show()

For Machine Learning

Plotting Loss vs Epoch
PYTHON
滚动查看更多
epochs = range(1, 11)
loss = [0.9, 0.7, 0.5, 0.4, 0.3, 0.25, 0.2, 0.18, 0.15, 0.13]
plt.plot(epochs, loss)
plt.title("Training Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.show()
Confusion Matrix (Heatmap)
PYTHON
滚动查看更多
from sklearn.metrics import confusion_matrix
import seaborn as sns

y_true = [0, 1, 2, 2, 0]
y_pred = [0, 0, 2, 2, 1]
cm = confusion_matrix(y_true, y_pred)    # Create confusion matrix
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')  # Heatmap visualization
plt.title("Confusion Matrix")
plt.show()
ROC Curve
PYTHON
滚动查看更多
from sklearn.metrics import roc_curve, auc

fpr, tpr, _ = roc_curve([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8])  # Compute ROC
roc_auc = auc(fpr, tpr)                 # Area under curve
plt.plot(fpr, tpr, label=f'AUC = {roc_auc:.2f}')
plt.plot([0, 1], [0, 1], 'k--')         # Diagonal line
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve")
plt.legend()
plt.show()

Saving Plots

PYTHON
滚动查看更多
plt.savefig("figure.png", dpi=300, bbox_inches='tight')  # Save plot to file

Show & Clear

PYTHON
滚动查看更多
plt.show()     # Show plot window
plt.clf()      # Clear current figure (useful when plotting in loops)
plt.close()    # Close figure window (useful in scripts or GUI apps)

More Useful Functions

FunctionUse Case
plt.fill_between(x, y1, y2)Fill area between curves
plt.axhline(y=value)Draw horizontal line at y
plt.axvline(x=value)Draw vertical line at x
plt.errorbar(x, y, yerr=...)Plot with error bars
plt.twinx()Create secondary y-axis
plt.subplots_adjust(...)Manually adjust subplot spacing
plt.gca()Get current axes
plt.gcf()Get current figure

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572