我的班级(下面)有一个奇怪的问题,它会在绘制的Matplotlib线上添加刻度线。似乎当轴纵横比设置为'equal'
时,显示坐标中的绘图会在交互式视图中混淆,以便"缩放"功能。平移和调整大小的工作正常,至少在最初校正显示之后,#34; Home"。
没有相等的宽高比设置就没有问题。
这是班级:
import numpy as np
from matplotlib import transforms
def get_perp_vec(u1, u2, direction=1):
"""Return the unit vector perpendicular to the vector u2-u1."""
x1, y1 = u1
x2, y2 = u2
vx, vy = x2-x1, y2-y1
v = np.linalg.norm((vx, vy))
wx, wy = -vy/v * direction, vx/v * direction
return wx, wy
class LineTicks:
def __init__(self, line, idx, **kwargs):
self.line = line
self.ticks = []
self.idx = idx
self.tick_length = 20
self.tick_styles = kwargs
self.ax = line.axes
self.ax.callbacks.connect('xlim_changed', self.on_change_lims)
self.ax.callbacks.connect('ylim_changed', self.on_change_lims)
cid = self.ax.figure.canvas.mpl_connect('resize_event',self.on_resize)
self.add_ticks(self.ax)
def add_ticks(self, ax):
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Transform to display coordinates
z =ax.transData.transform(np.array(self.line.get_data()).T)
x, y = zip(*z)
# Remove existing ticks
for tick in self.ticks:
ax.lines.remove(tick)
# Remove references to the ticks so they can be garbage-collected
self.ticks = []
for i in self.idx:
tx, ty = get_perp_vec((x[i-1], y[i-1]), (x[i], y[i]))
tx, ty = self.tick_length * tx, self.tick_length * ty
this_tick, = ax.plot((x[i],x[i]+tx), (y[i],y[i]+ty),
transform=transforms.IdentityTransform(), **self.tick_styles)
self.ticks.append(this_tick)
def on_change_lims(self, ax):
self.add_ticks(ax)
def on_resize(self, event):
self.add_ticks(self.ax)
当它不起作用的时候:
import matplotlib.pyplot as plt
theta = np.arange(0, 2*np.pi, np.pi/40)
x, y = np.cos(theta), np.sin(theta)
fig, ax = plt.subplots()
ax.set_aspect('equal')
circle_line, = ax.plot(x, y)
major_ticks = LineTicks(circle_line, range(0, len(x), 10), color='r', lw=2)
plt.show()
以供参考,以及它何时运作:
x = np.arange(0, 2*np.pi, np.pi/40)
y = np.sin(x)
fig, ax = plt.subplots()
circle_line, = ax.plot(x, y)
minor_ticks = LineTicks(circle_line, range(0, len(x), 2), lw=2, color='k')
plt.show()
我对set_aspect('equal')
的工作方式有什么看法,我应该怎么做?或者这是后端的错误? [Mac OS X,Python 3.3,Matplotlib 1.4.3]