2012-02-26 43 views
13

Trong hình bên dưới, mỗi đơn vị trong trục x thể hiện khoảng thời gian 10mins. Tôi muốn tùy chỉnh các nhãn của trục x, để nó hiển thị giờ, nghĩa là nó hiển thị một dấu ticker mỗi 6 đơn vị (60 phút). Tôi mới đến matplotlib. Có ai có thể giúp tôi không? Cảm ơn ~ enter image description hereTùy chỉnh trục x trong matplotlib

Đây là mã cho hình bên trên.

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() 

Trả lời

34

Có nhiều cách để thực hiện việc này.

Hãy bắt đầu với một âm mưu dụ:

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

Cách đơn giản để làm những gì bạn muốn sẽ là một cái gì đó như thế này:

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

Cách khác liên quan đến subclas hát định vị và mã cổ phiếu của matplotlib.

Vì mục đích của bạn, ví dụ ở trên là tốt.

Lợi thế của việc định vị và mã mới là trục sẽ tự động được chia tỷ lệ thành khoảng thời gian hợp lý của đơn vị "dx" bạn chỉ định. Nếu bạn đang sử dụng nó như một phần của một ứng dụng lớn hơn, nó có thể đáng giá. Đối với một cốt truyện duy nhất, đó là rắc rối nhiều hơn nó có giá trị.

Nếu bạn thực sự muốn đi con đường đó, tuy nhiên, bạn muốn làm điều gì đó như thế này:

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

Các vấn đề liên quan