python - 在 matplotlib 中自定义 x 轴

标签 python matplotlib

在下图中,x轴上的每个单位代表一个10分钟的间隔。我想自定义 x 轴的标签,以便它显示小时数,即它每 6 个单位(60 分钟)显示一个代码。我是 matplotlib 的新手。有人可以帮我吗?谢谢~ enter image description here

这是上图的代码。

x = arange(0, size_x, dx)
y = arange(0, size_y, dy)
X,Y = meshgrid(x, y)
Z = foo(x,y)
pcolor(X, Y, Z, cmap=cm.Reds)
colorbar()
axis([0,size_x-1,0,size_y-1])
show()

最佳答案

有不止一种方法可以做到这一点。

让我们从一个示例图开始:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Generate some data...
x, y = np.mgrid[:141, :101]
z = np.cos(np.hypot(x, y))

# Plot the figure...
plt.pcolormesh(x, y, z, cmap=mpl.cm.Reds)

plt.show()

enter image description here

做你想做的事情的简单方法是这样的:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Generate some data...
x, y = np.mgrid[:141, :101]
z = np.cos(np.hypot(x, y))

# Plot the figure...
plt.pcolormesh(x, y, z, cmap=mpl.cm.Reds)

# Set the ticks and labels...
ticks = np.arange(x.min(), x.max(), 6)
labels = range(ticks.size)
plt.xticks(ticks, labels)
plt.xlabel('Hours')

plt.show()

enter image description here

另一种方法涉及子类化 matplotlib 的定位器和代码。

对于您的目的,上面的示例很好。

制作新定位器和代码的优点是轴将自动缩放到您指定的“dx”单位的合理间隔内。如果您将它用作更大应用程序的一部分,那么它是值得的。对于单个地 block 来说,麻烦多于它的值(value)。

不过,如果你真的想走那条路,你会做这样的事情:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

def main():
    # Generate some data...
    x, y = np.mgrid[:141, :101]
    z = np.cos(np.hypot(x, y))

    # Plot the figure...
    fig, ax = plt.subplots()
    ax.pcolormesh(x, y, z, cmap=mpl.cm.Reds)
    ax.set_xlabel('Hours')

    ax.xaxis.set_major_locator(ScaledLocator(dx=6))
    ax.xaxis.set_major_formatter(ScaledFormatter(dx=6))

    plt.show()

class ScaledLocator(mpl.ticker.MaxNLocator):
    """
    Locates regular intervals along an axis scaled by *dx* and shifted by
    *x0*. For example, this would locate minutes on an axis plotted in seconds
    if dx=60.  This differs from MultipleLocator in that an approriate interval
    of dx units will be chosen similar to the default MaxNLocator.
    """
    def __init__(self, dx=1.0, x0=0.0):
        self.dx = dx
        self.x0 = x0
        mpl.ticker.MaxNLocator.__init__(self, nbins=9, steps=[1, 2, 5, 10])

    def rescale(self, x):
        return x / self.dx + self.x0
    def inv_rescale(self, x):
        return  (x - self.x0) * self.dx

    def __call__(self): 
        vmin, vmax = self.axis.get_view_interval()
        vmin, vmax = self.rescale(vmin), self.rescale(vmax)
        vmin, vmax = mpl.transforms.nonsingular(vmin, vmax, expander = 0.05)
        locs = self.bin_boundaries(vmin, vmax)
        locs = self.inv_rescale(locs)
        prune = self._prune
        if prune=='lower':
            locs = locs[1:]
        elif prune=='upper':
            locs = locs[:-1]
        elif prune=='both':
            locs = locs[1:-1]
        return self.raise_if_exceeds(locs)

class ScaledFormatter(mpl.ticker.OldScalarFormatter):
    """Formats tick labels scaled by *dx* and shifted by *x0*."""
    def __init__(self, dx=1.0, x0=0.0, **kwargs):
        self.dx, self.x0 = dx, x0

    def rescale(self, x):
        return x / self.dx + self.x0

    def __call__(self, x, pos=None):
        xmin, xmax = self.axis.get_view_interval()
        xmin, xmax = self.rescale(xmin), self.rescale(xmax)
        d = abs(xmax - xmin)
        x = self.rescale(x)
        s = self.pprint_val(x, d)
        return s

if __name__ == '__main__':
    main()

enter image description here

关于python - 在 matplotlib 中自定义 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9451395/

相关文章:

python - 使用matplotlib.pyplot制作一维波动方程的动画

python - Python 中 base64 编码/解码的额外新行?

python比较两个矩阵

Python Mysqld : After reinstall, 仅当变量元组有尾随逗号时才有效

python - 如何在 tkinter sqlite3 中重新索引主键

python - 我可以在 Google 应用引擎上将 opencv 与 python 一起使用吗?

python - 向 Pandas DataFrame 箱线图添加图例

matplotlib - 在 IJulia 中禁用 PyPlot.jl 图形的自动显示

python - Mac 上的 matplotlib QtDesigner 小部件?

python - 如何创建具有方位角、天顶角和平均权重值的极坐标图?