gpt4 book ai didi

python - Matplotlib - 更改自动轴范围

转载 作者:行者123 更新时间:2023-12-04 23:41:55 26 4
gpt4 key购买 nike

我对数据使用自动轴范围。

例如,当我在 -29 和 +31 之间使用 x 数据时

ax = plt.gca()
xsta, xend = ax.get_xlim()

我得到 -30 和 40,它们没有恰本地描述数据范围。我希望看到轴范围四舍五入为 5,即限制为 -30 和 35。

有可能这样做吗?或者,是否有可能获得 x 轴数据的精确范围(-29,31),然后编写一个算法来手动更改(使用 set_xlim )?

感谢帮助。

最佳答案

首先,让我们建立一个简单的例子:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
plt.show()

enter image description here

如果您想知道手动指定内容的数据范围,您可以使用:
ax.xaxis.get_data_interval()
ax.yaxis.get_data_interval()

但是,想要更改为数据限制的简单填充是很常见的。在这种情况下,请使用 ax.margins(some_percentage) .例如,这将用数据范围的 5% 填充限制:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
ax.margins(0.05)
plt.show()

enter image description here

要返回原始场景,您可以手动使轴限制仅使用 5 的倍数(但不更改刻度等):
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])

multiplier = 5.0
for axis, setter in [(ax.xaxis, ax.set_xlim), (ax.yaxis, ax.set_ylim)]:
vmin, vmax = axis.get_data_interval()
vmin = multiplier * np.floor(vmin / multiplier)
vmax = multiplier * np.ceil(vmax / multiplier)
setter([vmin, vmax])

plt.show()

enter image description here

我们也可以通过为每个轴子类化定位器来完成同样的事情:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoLocator

class MyLocator(AutoLocator):
def view_limits(self, vmin, vmax):
multiplier = 5.0
vmin = multiplier * np.floor(vmin / multiplier)
vmax = multiplier * np.ceil(vmax / multiplier)
return vmin, vmax

fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])

ax.xaxis.set_major_locator(MyLocator())
ax.yaxis.set_major_locator(MyLocator())
ax.autoscale()

plt.show()

关于python - Matplotlib - 更改自动轴范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34884396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com