坐标轴与图形精修

通过日期刻度、内嵌 axes 与坐标轴移位等技巧,精细控制图表的每一处细节。

日期格式内嵌图坐标轴移位函数图像
48 小时股票价格

图表作品

共 5 张图表 · 点击图片可放大,展开可查看完整代码

01

48 小时股票价格

使用日期定位器与格式化器,让时间轴按小时显示。

查看 Python 代码 +
import numpy as np
from datetime import datetime,timedelta
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, HourLocator
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 = plt.figure()
ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))
ax.plot(x_time,y_price,'g-o')
ax.set_title('48小时股票价格数据')
ax.set_xlabel('时间(h)')
date_fmt = DateFormatter('%Y-%m-%D %H:%M')
ax.xaxis.set_major_locator(HourLocator(interval=12))
ax.xaxis.set_major_formatter(date_fmt)
ax.xaxis.set_minor_locator(HourLocator(interval = 2))
ax.tick_params(axis='x',which='major',direction='out',length=10,width=2,color='blue',labelrotation=15)
ax.tick_params(axis='x',which='minor',direction='in',length=5,color='red')
plt.grid(axis='both',color = 'gray',linestyle='--',linewidth=0.3,alpha=0.8)
plt.show()
02

全国与华东销量对比

用 add_axes 在主图右上角嵌入局部放大图,突出区域数据。

查看 Python 代码 +
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()
ax1 = fig.add_axes((0.1, 0.1, 0.8, 0.8))
ax1.plot(x_all, y_all_sales, 'b-s', label='全国总销量')
ax1.set_title('全国及华东地区销量对比')
ax1.set_xlabel('月份')
ax1.set_ylabel('全国销量')
ax1.legend()
ax2 = fig.add_axes((0.7, 0.7, 0.2, 0.2))
ax2.plot(x_all, y_east_sales, 'r-o', label='华东区销量')
ax2.set_title('华东地区', fontsize=9)
ax2.tick_params(labelsize=8)
ax2.legend(fontsize=8)
plt.show()
03

编程语言投票排行

水平条形图配合数据标签,直观展示各语言的得票情况。

查看 Python 代码 +
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 = plt.figure()
ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))
bars = ax.barh(y_pos, votes, height=0.5)
ax.set_yticks(y_pos)
ax.set_yticklabels(languages)
ax.bar_label(bars, padding=3)
ax.set_title('编程语言投票数据')
ax.set_xlabel('投票人数')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(axis='y', length=0)
plt.show()
04

二次函数图像

移动坐标轴到原点并隐藏边框,绘制简洁的函数曲线。

查看 Python 代码 +
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 = plt.figure()
ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))
ax.plot(x, y, label='$y=x^2$')
ax.set_xlim(-6, 6)
ax.set_ylim(-2, 30)
ax.set_title('二次函数图像')
ax.legend()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
plt.show()
05

正切函数图像

处理渐近线附近的数值,用 π 刻度标签绘制正切曲线。

查看 Python 代码 +
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)
y_plot = np.where(np.abs(y) > 4, np.nan, y)
fig = plt.figure()
ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))
ax.plot(x,y_plot,label = r'$y=\tan(x)$')
ax.set_ylim(-4,4)
ax.set_xticks( [-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
ax.set_title('正切函数图像')
ax.set_xticklabels([r'$-\pi$',r'$-\frac{\pi}{2}$','0',r'$\frac{\pi}{2}$',r'$\pi$'])
ax.legend()
ax.grid(True, linestyle='--', alpha=0.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
plt.show()