python-3.x - 如何在 Matplotlib 中设置轴的 view_limits/range

标签 python-3.x matplotlib

我想要轴上最后一个刻度位置前后的一些空间。例如,我只会使用 axis.set_xlim() 但这会干扰我的(自定义)定位器并重新运行刻度生成。我找到并覆盖了定位器类的 view_limits() 方法,但它们似乎不会被自动调用,当手动调用时,它们对结果图没有任何影响。我搜索了文档和源代码,但没有找到解决方案。我错过了什么吗?

为了更大的画面,我想要一个定位器,它在刻度之前和之后给我一些空间,并选择刻度点,这些刻度点是像 MultipleLocator 这样的“基数”的倍数,但如果刻度数超过一个,则自动缩放基数指定值。如果有另一种方法可以在不对定位器进行子类化的情况下实现这一点,我会洗耳恭听:)。

这是我的子类定位器的示例代码,其中覆盖了 view_limits-method:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator

class MyLocator(MaxNLocator):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def view_limits(self, dmin, dmax):
        bins = self.bin_boundaries(dmin, dmax)
        step = bins[1] - bins[0]
        result = np.array([bins[0] - step, bins[-1] + step])
        print(result)
        return result

a = 10.0
b = 99.0

t = np.arange(a, b, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

loc = MyLocator(9)

fig, ax = plt.subplots()
plt.plot(t, s)

ax.xaxis.set_major_locator(loc)
loc.autoscale()  # results in [   0.  110.] but doesnt change the plot
plt.show()

最佳答案

不确定,如果我完全理解你的问题是什么,但如果你只想添加额外的空间,你仍然可以使用 MaxNLocator 并像这里一样手动添加该空间:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator

a = 10.0
b = 99.0

t = np.arange(a, b, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

loc = MaxNLocator(9)

fig, ax = plt.subplots()
plt.plot(t, s)

ax.xaxis.set_major_locator(loc)
ticks = ax.get_xticks()
newticks = np.zeros(len(ticks)+2)
newticks[0] = ticks[0]- (ticks[1]-ticks[0])
newticks[-1] = ticks[-1]+ (ticks[1]-ticks[0])
newticks[1:-1] = ticks
ax.set_xticks(newticks)

plt.show()

关于python-3.x - 如何在 Matplotlib 中设置轴的 view_limits/range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39765892/

相关文章:

python - 使用 skimage 从多边形中提取图像片段

python - 如何在 pandas 和 matplotlib 中使用 1e7 避免轴值

matplotlib绘制椭圆轮廓

linux - 如何从 screen session 中运行的程序获取控制台输出?

python - 使用 Azure 托管服务标识 (MSI) 连接 Azure SQL Server 数据库

python - 在 tkinter 上的同一窗口中绘制图形和表格

python - 使用 maltpoltlib 对带有轮廓的 pcolormesh 进行动画处理

python-3.x - Visual Studio Python "Failed to launch the Python Process, please validate the path ' python'' & 错误 : spawn python ENOENT

python-3.x - 如何划分两个聚合总和数据帧

python - 项目分配给字节对象?