Matplotlib - 设置限制
Matplotlib - 设置坐标轴范围
Section titled “Matplotlib - 设置坐标轴范围”默认情况下,Matplotlib 会自动确定 x 轴和 y 轴的范围(limits),以包含所有绘制的数据点。然而,为了更好地控制可视化效果,例如聚焦于特定区域或确保多个图的一致性,你通常需要手动设置这些范围。
使用 set_xlim() 和 set_ylim()
Section titled “使用 set_xlim() 和 set_ylim()”在面向对象 API 中,设置坐标轴范围的主要方法是 ax.set_xlim() 和 ax.set_ylim(),它们在 Axes 对象(ax)上调用。
ax.set_xlim(left, right):设置 x 轴的最小值(left)和最大值(right)。ax.set_ylim(bottom, top):设置 y 轴的最小值(bottom)和最大值(top)。
你也可以传入一个元组(tuple)或列表(list):ax.set_xlim((left, right))。
若只想设置其中一个范围,可以使用 None 或省略你想让 Matplotlib 自动调整的那个参数(例如,ax.set_xlim(left=0) 将 x 轴最小值设置为 0,最大值则自动确定)。
示例:自动范围 vs. 手动范围
Section titled “示例:自动范围 vs. 手动范围”让我们绘制一个指数函数,看看设置范围如何改变视图。
import matplotlib.pyplot as pltimport numpy as np
# Datax = np.arange(1, 10)y = np.exp(x)
# --- Plot 1: Autoscaled Limits ---fig1, ax1 = plt.subplots(figsize=(6, 4))ax1.plot(x, y, 'bo-')ax1.set_title('Exponential Plot (Autoscaled Limits)')ax1.set_xlabel('x')ax1.set_ylabel('exp(x)')ax1.grid(True)print(f"Autoscaled X limits: {ax1.get_xlim()}")print(f"Autoscaled Y limits: {ax1.get_ylim()}")
# --- Plot 2: Manually Set Limits ---fig2, ax2 = plt.subplots(figsize=(6, 4))ax2.plot(x, y, 'rs--')ax2.set_title('Exponential Plot (Manual Limits)')ax2.set_xlabel('x')ax2.set_ylabel('exp(x)')
# Set specific limitsax2.set_xlim(0, 12) # Extend x-axis beyond data rangeax2.set_ylim(-1000, 10000) # Set y-axis range, starting below zero
ax2.grid(True)print(f"Manual X limits: {ax2.get_xlim()}")print(f"Manual Y limits: {ax2.get_ylim()}")
plt.show() # Show both figures运行这段代码将生成两个图:
- 第一个图(‘Autoscaled Limits’,自动范围)的坐标轴将紧密地围绕数据点(x 大约从 1 到 9,y 大约从接近 0 到超过 8000)。
- 第二个图(‘Manual Limits’,手动范围)将显示相同的数据,但 x 轴范围从 0 到 12,y 轴范围从 -1000 到 10000。这根据特定要求提供了更多上下文或聚焦了视图。
使用 axis()
Section titled “使用 axis()”ax.axis() 方法提供了一种便捷的方式来获取或设置坐标轴属性,包括范围。
ax.axis():返回当前的范围(xmin, xmax, ymin, ymax)。ax.axis([xmin, xmax, ymin, ymax]):一次性设置所有四个范围。ax.axis('tight'):将范围紧密设置在数据周围。ax.axis('equal'):设置长宽比(aspect ratio)为 1:1,并相应调整范围。ax.axis('scaled'):通过改变图形尺寸来设置长宽比为 1:1。ax.axis('off'):关闭坐标轴线和标签。
# Example using axis()fig, ax = plt.subplots()ax.plot(x, y, 'gd:')ax.set_title('Using ax.axis()')
# Set limits using axis()ax.axis([0, 15, 0, 12000])
ax.grid(True)plt.show()设置坐标轴范围是控制 Matplotlib 中数据可视化呈现的基本技术。