Matplotlib · 5 Exercises
让数据,
安静地说话。
将 Notebook 中的五组 Matplotlib 练习整理为一页式可视化报告:从时间序列、双坐标对比、分类排序,到函数曲线。整体采用纯白与灰阶,让结构与趋势成为唯一主角。
05可视化图表
100%本地自包含
2025练习年份
Contents
- 01股票价格 48 小时波动
- 02全国与华东区销量
- 03最喜爱编程语言
- 04函数 y = x²
- 05函数 y = tan(x)
01—05按 Notebook 单元格顺序排列
EXERCISE 01
股票价格 48 小时波动图
每 2 小时采样一次,共 25 个观测点。保留主次刻度的思路,以简洁灰阶呈现价格在 99.5 至 103.0 之间的起伏。
时间序列 · 折线
起始价100.0
最高价103.0
最低价99.5
波动幅度3.5
平均价格101.1
查看 Notebook 源码
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
base = datetime(2025, 1, 1, 0)
x_time = np.array([base + timedelta(hours=i*2) for i in range(25)])
y_price = np.array([100.0, 100.2, 101.0, 100.5, 100.8, 102.0, 101.5, 101.8,
101.3, 100.9, 100.0, 99.5, 100.0, 99.8, 100.5, 101.2,
101.0, 101.5, 102.5, 103.0, 102.8, 102.5, 102.0, 101.5, 101.8])
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(x_time, y_price, 'g-o')
ax.xaxis.set_major_locator(mdates.HourLocator(interval=12))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M"))
ax.xaxis.set_minor_locator(mdates.HourLocator(interval=2))
ax.tick_params(axis="x", which="major", direction="out",
color="blue", length=10, width=2, labelrotation=15)
ax.tick_params(axis="x", which="minor", direction="in", color="red", length=5)
ax.grid(True)
ax.set_title("练习1:股票价格48小时波动图(定制刻度)")
ax.set_xlabel("日期与时间")
ax.set_ylabel("股票价格")
plt.tight_layout()
plt.show()
EXERCISE 02
全国总销量与华东区销量
主图展示 1—12 月全国总销量,右上角嵌入小坐标系单独呈现华东区销量,用于对比整体趋势与区域表现。
双坐标系 · 嵌入图
全国峰值90 万件
峰值月份8 月
华东峰值40 万件
华东峰值占比44.4%
查看 Notebook 源码
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x_all = np.arange(1, 13)
y_all_sales = np.array([50, 55, 60, 65, 75, 80, 85, 90, 80, 70, 65, 70])
y_east_sales = np.array([20, 22, 25, 28, 30, 35, 38, 40, 35, 30, 28, 30])
fig = plt.figure(figsize=(10,6))
ax_main = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax_main.plot(x_all, y_all_sales, 'b-s', label="全国总销量")
ax_main.set_title("练习2:全国总销量与华东区销量")
ax_main.set_xlabel("月份")
ax_main.set_ylabel("总销量(万件)")
ax_main.legend()
ax_inset = fig.add_axes([0.55,0.55,0.32,0.32])
ax_inset.plot(x_all, y_east_sales, 'r-o', label="华东区销量")
ax_inset.set_title("华东区销量")
ax_inset.set_xlabel("月份")
ax_inset.set_ylabel("销量(万件)")
ax_inset.tick_params(labelsize=8)
ax_inset.legend()
plt.show()
EXERCISE 03
最喜爱的编程语言
隐藏顶部与右侧轴脊的水平条形图,保留语言标签与票数标注。数据顺序与 PDF 输出保持一致。
分类数据 · 条形
总票数1510
第一名Python
第一名票数450
第一名占比29.8%
查看 Notebook 源码
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
languages = ['Python', 'JavaScript', 'Java', 'C#', 'Go', 'TypeScript']
y_pos = np.arange(len(languages))
votes = np.array([450, 380, 290, 180, 120, 90])
fig, ax = plt.subplots(figsize=(8,6))
bars = ax.barh(y_pos, votes, color="teal")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.tick_params(axis='y', length=0)
ax.set_yticks(y_pos, labels=languages)
ax.set_xlabel("得票数")
ax.set_title("练习3:最喜爱的编程语言(隐藏轴脊)")
for bar in bars:
width = bar.get_width()
ax.text(width + 5, bar.get_y() + bar.get_height()/2,
f"{int(width)}", va="center")
plt.tight_layout()
plt.show()
EXERCISE 04
二次函数 y = x²
将左侧与底部坐标轴移动到数据原点 (0, 0),并隐藏顶部、右侧轴脊,突出抛物线的对称结构。
数学函数 · 曲线
函数y = x²
顶点(0, 0)
对称轴x = 0
值域[0, +∞)
查看 Notebook 源码
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(-5, 5, 100)
y = x ** 2
fig, ax = plt.subplots(figsize=(7,6))
ax.plot(x, y, 'b-', label=r'$y=x^2$')
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_position(("data", 0))
ax.spines["bottom"].set_position(("data", 0))
ax.set_xlim(-5, 5)
ax.set_ylim(-1, 26)
ax.legend(fontsize=12)
ax.set_title(r"练习4:函数 $y=x^{2}$")
plt.tight_layout()
plt.show()
EXERCISE 05
正切函数 y = tan(x)
在 [-π, π] 区间内绘制正切曲线,标注 ±π/2 两条渐近线,并将纵轴范围限制在 [-4, 4] 以内。
数学函数 · 渐近线
函数y = tan(x)
周期π
零点−π, 0, π
渐近线x = ±π/2
查看 Notebook 源码
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(-np.pi + 0.1, np.pi - 0.1, 200)
y = np.tan(x)
fig, ax = plt.subplots(figsize=(8,6))
ax.plot(x, y, 'g-', label=r'$y=\tan(x)$')
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_position(("data", 0))
ax.spines["bottom"].set_position(("data", 0))
ax.set_ylim(-4, 4)
xtick_values = [-np.pi, -np.pi/2, 0, np.pi/2, np.pi]
xtick_labels = [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$']
ax.set_xticks(xtick_values)
ax.set_xticklabels(xtick_labels)
ax.grid(True)
ax.legend()
ax.set_title("练习5:函数 $y=\\tan(x)$ (综合练习)")
plt.tight_layout()
plt.show()