您可以通过matplotlib 事件处理实现您想要的。您必须分别捕捉缩放和调整大小事件。同时考虑两者有点棘手,但并非不可能。下面是一个带有两个子图的示例,左侧是折线图,右侧是散点图。缩放(因子)和调整图形大小(fig_factor)都会根据图形大小和 x 和 y 限制中的缩放因子重新缩放点。由于定义了两个限制——一个用于x,一个用于y 方向,我在这里使用了这两个因素各自的最小值。如果您希望使用更大的因子进行缩放,请将两个事件函数中的 min 更改为 max。
from matplotlib import pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=1, ncols = 2)
ax1,ax2 = axes
fig_width = fig.get_figwidth()
fig_height = fig.get_figheight()
fig_factor = 1.0
##saving some values
xlim = dict()
ylim = dict()
lines = dict()
line_sizes = dict()
paths = dict()
point_sizes = dict()
## a line plot
x1 = np.linspace(0,np.pi,30)
y1 = np.sin(x1)
lines[ax1] = ax1.plot(x1, y1, 'ro', markersize = 3, alpha = 0.8)
xlim[ax1] = ax1.get_xlim()
ylim[ax1] = ax1.get_ylim()
line_sizes[ax1] = [line.get_markersize() for line in lines[ax1]]
## a scatter plot
x2 = np.random.normal(1,1,30)
y2 = np.random.normal(1,1,30)
paths[ax2] = ax2.scatter(x2,y2, c = 'b', s = 20, alpha = 0.6)
point_sizes[ax2] = paths[ax2].get_sizes()
xlim[ax2] = ax2.get_xlim()
ylim[ax2] = ax2.get_ylim()
def on_resize(event):
global fig_factor
w = fig.get_figwidth()
h = fig.get_figheight()
fig_factor = min(w/fig_width,h/fig_height)
for ax in axes:
lim_change(ax)
def lim_change(ax):
lx = ax.get_xlim()
ly = ax.get_ylim()
factor = min(
(xlim[ax][1]-xlim[ax][0])/(lx[1]-lx[0]),
(ylim[ax][1]-ylim[ax][0])/(ly[1]-ly[0])
)
try:
for line,size in zip(lines[ax],line_sizes[ax]):
line.set_markersize(size*factor*fig_factor)
except KeyError:
pass
try:
paths[ax].set_sizes([s*factor*fig_factor for s in point_sizes[ax]])
except KeyError:
pass
fig.canvas.mpl_connect('resize_event', on_resize)
for ax in axes:
ax.callbacks.connect('xlim_changed', lim_change)
ax.callbacks.connect('ylim_changed', lim_change)
plt.show()
代码已在 Pyton 2.7 和 3.6 中使用 matplotlib 2.1.1 进行了测试。
编辑
在下面的 cmets 和 this answer 的推动下,我创建了另一个解决方案。这里的主要思想是只使用一种类型的事件,即draw_event。起初,这些图在缩放时没有正确更新。同样ax.draw_artist() 后跟fig.canvas.draw_idle() 就像链接答案中的那样并没有真正解决问题(但是,这可能是特定于平台/后端的)。相反,每当缩放发生变化时,我都会对fig.canvas.draw() 添加一个额外的调用(if 语句可防止无限循环)。
此外,请避免使用所有全局变量,我将所有内容都包装到一个名为MarkerUpdater 的类中。每个Axes 实例都可以单独注册到MarkerUpdater 实例,因此您还可以在一个图中有多个子图,其中一些已更新,有些未更新。我还修复了另一个错误,散点图中的点缩放错误——它们应该是二次的,而不是线性的 (see here)。
最后,由于之前的解决方案中缺少它,我还为标记的 alpha 值添加了更新。这不像标记大小那样直接,因为alpha 的值不能大于 1.0。出于这个原因,在我的实现中,alpha 值只能从原始值减少。在这里,我实现了它,当图形大小减小时alpha 减小。请注意,如果没有为 plot 命令提供 alpha 值,则艺术家将 None 存储为 alpha 值。在这种情况下,自动 alpha 调整已关闭。
应该更新哪些Axes 可以使用features 关键字定义——请参阅下面if __name__ == '__main__': 以了解如何使用MarkerUpdater 的示例。
编辑 2
正如@ImportanceOfBeingErnest 所指出的,在使用TkAgg 后端时,我的答案存在无限递归问题,并且显然缩放时图形无法正确刷新的问题(我无法验证,所以可能是依赖于实现的)。删除 fig.canvas.draw() 并在循环中添加 ax.draw_artist(ax) 覆盖 Axes 实例,而是解决了这个问题。
编辑 3
我更新了代码以解决一个持续存在的问题,即在 draw_event 上未正确更新图形。该修复程序取自此答案,但经过修改后也适用于多个数字。
就如何获得因子的解释而言,MarkerUpdater 实例包含一个dict,它为每个Axes 实例存储图形尺寸和添加@ 时的轴限制987654357@。在draw_event 上,例如在调整图形大小或用户放大数据时触发,检索图形大小和轴限制的新(当前)值并计算(并存储)比例因子,例如放大和增加图形大小会使标记变大。因为 x 和 y 维度可能以不同的速率变化,所以我使用 min 来选择两个计算因子之一,并始终根据图形的原始大小进行缩放。
如果您希望您的 alpha 使用不同的函数进行缩放,您可以轻松更改调整 alpha 值的线条。例如,如果你想要一个幂律而不是线性递减,你可以写path.set_alpha(alpha*facA**n),其中 n 是幂。
from matplotlib import pyplot as plt
import numpy as np
##plt.switch_backend('TkAgg')
class MarkerUpdater:
def __init__(self):
##for storing information about Figures and Axes
self.figs = {}
##for storing timers
self.timer_dict = {}
def add_ax(self, ax, features=[]):
ax_dict = self.figs.setdefault(ax.figure,dict())
ax_dict[ax] = {
'xlim' : ax.get_xlim(),
'ylim' : ax.get_ylim(),
'figw' : ax.figure.get_figwidth(),
'figh' : ax.figure.get_figheight(),
'scale_s' : 1.0,
'scale_a' : 1.0,
'features' : [features] if isinstance(features,str) else features,
}
ax.figure.canvas.mpl_connect('draw_event', self.update_axes)
def update_axes(self, event):
for fig,axes in self.figs.items():
if fig is event.canvas.figure:
for ax, args in axes.items():
##make sure the figure is re-drawn
update = True
fw = fig.get_figwidth()
fh = fig.get_figheight()
fac1 = min(fw/args['figw'], fh/args['figh'])
xl = ax.get_xlim()
yl = ax.get_ylim()
fac2 = min(
abs(args['xlim'][1]-args['xlim'][0])/abs(xl[1]-xl[0]),
abs(args['ylim'][1]-args['ylim'][0])/abs(yl[1]-yl[0])
)
##factor for marker size
facS = (fac1*fac2)/args['scale_s']
##factor for alpha -- limited to values smaller 1.0
facA = min(1.0,fac1*fac2)/args['scale_a']
##updating the artists
if facS != 1.0:
for line in ax.lines:
if 'size' in args['features']:
line.set_markersize(line.get_markersize()*facS)
if 'alpha' in args['features']:
alpha = line.get_alpha()
if alpha is not None:
line.set_alpha(alpha*facA)
for path in ax.collections:
if 'size' in args['features']:
path.set_sizes([s*facS**2 for s in path.get_sizes()])
if 'alpha' in args['features']:
alpha = path.get_alpha()
if alpha is not None:
path.set_alpha(alpha*facA)
args['scale_s'] *= facS
args['scale_a'] *= facA
self._redraw_later(fig)
def _redraw_later(self, fig):
timer = fig.canvas.new_timer(interval=10)
timer.single_shot = True
timer.add_callback(lambda : fig.canvas.draw_idle())
timer.start()
##stopping previous timer
if fig in self.timer_dict:
self.timer_dict[fig].stop()
##storing a reference to prevent garbage collection
self.timer_dict[fig] = timer
if __name__ == '__main__':
my_updater = MarkerUpdater()
##setting up the figure
fig, axes = plt.subplots(nrows = 2, ncols =2)#, figsize=(1,1))
ax1,ax2,ax3,ax4 = axes.flatten()
## a line plot
x1 = np.linspace(0,np.pi,30)
y1 = np.sin(x1)
ax1.plot(x1, y1, 'ro', markersize = 10, alpha = 0.8)
ax3.plot(x1, y1, 'ro', markersize = 10, alpha = 1)
## a scatter plot
x2 = np.random.normal(1,1,30)
y2 = np.random.normal(1,1,30)
ax2.scatter(x2,y2, c = 'b', s = 100, alpha = 0.6)
## scatter and line plot
ax4.scatter(x2,y2, c = 'b', s = 100, alpha = 0.6)
ax4.plot([0,0.5,1],[0,0.5,1],'ro', markersize = 10) ##note: no alpha value!
##setting up the updater
my_updater.add_ax(ax1, ['size']) ##line plot, only marker size
my_updater.add_ax(ax2, ['size']) ##scatter plot, only marker size
my_updater.add_ax(ax3, ['alpha']) ##line plot, only alpha
my_updater.add_ax(ax4, ['size', 'alpha']) ##scatter plot, marker size and alpha
plt.show()