第六章:坐标轴定制

淡紫色渐变主题 - 坐标轴位置、刻度样式、轴脊控制等高级定制功能

📊 坐标轴概述

matplotlib的坐标轴由四个轴脊(spines)组成:上(top)、下(bottom)、左(left)、右(right)。每个轴脊都有对应的刻度(ticks)和标签(labels)。

4
轴脊数量
2
坐标轴
8
刻度线
import matplotlib.pyplot as plt
ax = plt.gca()
print(ax.spines) # 显示轴脊信息

📍 向任意位置添加坐标轴

可以使用plt.axes()方法在指定位置添加坐标轴,参数格式为[left, bottom, width, height]。

# 添加子图到指定位置
ax1 = plt.axes([0.1, 0.1, 0.8, 0.8])
ax2 = plt.axes([0.2, 0.2, 0.3, 0.3])

⚙️ 刻度定制

深圳市24小时平均风速数据展示,演示时间刻度的定制技术。

# 定制时间刻度
from matplotlib.dates import DateFormatter, HourLocator
ax.xaxis.set_major_locator(HourLocator(interval=2))
ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))

🎯 轴脊控制

正弦与余弦曲线展示,演示轴脊的隐藏和移动技术。

# 隐藏和移动轴脊
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))