matplotlib - 提前了解 x 轴范围
问题描述
我有一个数组中的数据x
,我想提前知道 Matplotlib 为 x 轴选择的 x 限制。
可能吗?如果可能的话,怎么做?
加分点,它取决于轴的物理长度吗?
解决方案
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
推荐阅读
- javascript - 从角度画布在浏览器窗口外绘图?
- reactjs - 如何避免在最高级别的 React 组件中包含所有方法?
- javascript - Jquery,错误发生未捕获类型错误:无法读取 null 的属性“defaultView”
- sdn - 无法在主机之间 ping
- project-reactor - 没有任何参数的 Flux.repeat() 的用例是什么?
- c# - 如何将两个模型添加到一个视图?
- firebase - 扑火商店得到最后一个结果
- javascript - 对我在 redux 中不可序列化的内容感到困惑(redux 错误)
- html - 上下动画
- typescript - 具有逻辑或的打字稿 lambda 函数