简介
本实验将教你如何使用 Matplotlib 中的add_floating_axis函数为图表添加浮动轴,该浮动轴可用于显示有关图表的其他信息。具体来说,你将学习如何调整刻度标签和轴标签的填充,以及如何调整浮动轴上刻度的位置。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。
导入库
首先,导入必要的库,包括matplotlib.pyplot、numpy和mpl_toolkits.axisartist。
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.axisartist as axisartist
定义设置轴的函数
接下来,定义setup_axes()函数,该函数用于设置图表的极坐标投影。此函数使用GridHelperCurveLinear在矩形框中创建极坐标投影。它还设置了图表的界限并返回ax1对象。
def setup_axes(fig, rect):
## 定义极坐标轴变换和极值查找器
tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf))
## 定义网格定位器和格式化器
grid_locator1 = angle_helper.LocatorDMS(12)
grid_locator2 = grid_finder.MaxNLocator(5)
tick_formatter1 = angle_helper.FormatterDMS()
## 定义 GridHelperCurveLinear
grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1)
## 创建轴对象并设置其界限
ax1 = fig.add_subplot(rect, axes_class=axisartist.Axes, grid_helper=grid_helper)
ax1.axis[:].set_visible(False)
ax1.set_aspect(1.)
ax1.set_xlim(-5, 12)
ax1.set_ylim(-5, 10)
return ax1
定义添加浮动轴函数
定义add_floating_axis函数,该函数用于向图表添加一个浮动轴。此函数将ax1对象作为参数传入,并返回axis对象。
def add_floating_axis(ax1):
## 定义浮动轴
ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 30)
axis.label.set_text(r"$\theta = 30^{\circ}$")
axis.label.set_visible(True)
return axis
为刻度标签添加填充
在这一步中,为浮动轴上的刻度标签添加填充。这可以通过将major_ticklabels对象的pad属性设置为所需的填充值来实现。
## 为刻度标签添加填充
fig = plt.figure(figsize=(9, 3.))
fig.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99, wspace=0.01, hspace=0.01)
ax1 = setup_axes(fig, rect=121)
axis = add_floating_axis(ax1)
ax1 = setup_axes(fig, rect=122)
axis = add_floating_axis(ax1)
axis.major_ticklabels.set_pad(10)
plt.show()
调整轴标签的填充
在这一步中,调整浮动轴上轴标签的填充。这可以通过将label对象的pad属性设置为所需的填充值来完成。
## 调整轴标签的填充
fig = plt.figure(figsize=(9, 3.))
fig.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99, wspace=0.01, hspace=0.01)
ax1 = setup_axes(fig, rect=121)
axis = add_floating_axis(ax1)
ax1 = setup_axes(fig, rect=122)
axis = add_floating_axis(ax1)
axis.label.set_pad(20)
plt.show()
调整刻度位置
在这一步中,调整浮动轴上刻度的位置。这可以通过将major_ticks对象的tick_out属性设置为True来实现。
## 调整刻度位置
fig = plt.figure(figsize=(9, 3.))
fig.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99, wspace=0.01, hspace=0.01)
ax1 = setup_axes(fig, rect=121)
axis = add_floating_axis(ax1)
ax1 = setup_axes(fig, rect=122)
axis = add_floating_axis(ax1)
axis.major_ticks.set_tick_out(True)
plt.show()
总结
在本实验中,你学习了如何使用 Matplotlib 中的add_floating_axis函数向图表添加浮动轴。你还学习了如何调整刻度标签和轴标签的填充,以及如何调整浮动轴上刻度的位置。完成本实验后,你应该能够创建带有浮动轴的定制图表,这些图表可以显示有关该图表的更多信息。