首页 > 解决方案 > 提前了解 x 轴范围

问题描述

我有一个数组中的数据x,我想提前知道 Matplotlib 为 x 轴选择的 x 限制。

可能吗?如果可能的话,怎么做?

加分点,它取决于轴的物理长度吗?

标签: matplotlib

解决方案


Matplotlib 将边距添加到 x 范围。默认这些边距为 0.05(双向)。这不取决于轴在屏幕上的长度。请注意,某些功能会干扰默认行为。例如,只有正条形的水平条形图将从处开始,x=0以避免“漂浮在空中”。

下面是一些代码,它首先“预测”限制,然后写出有效限制:

from matplotlib import pyplot as plt
import numpy as  np

x = np.random.normal(50, 10, 5)

fig, ax = plt.subplots()

x_margin, y_margin = ax.margins()
x_delta = (x.max() - x.min()) * x_margin
print(f"Default x limits: {x.min() - x_delta:.5f}, {x.max() + x_delta:.5f} ")
ax.plot(x, np.random.rand(x.size))
fig.canvas.draw()
xlims = ax.get_xlim()
print(f"Effective x limits: {xlims[0]:.5f} {xlims[1]:.5f} ")

示例输出:

Default x limits: 43.48084, 58.02320 
Effective x limits: 43.48084 58.02320 

示例图


推荐阅读