在 xy 图表上探索具有多个点的数据集时,我可以调整 alpha 和/或标记大小,以快速直观地了解这些点聚集最密集的位置。但是,当我放大或使窗口变大时,需要不同的 alpha 和/或标记大小来提供相同的视觉印象。
当我放大窗口或放大数据时,如何增加 alpha 值和/或标记大小?我在想,如果我将窗口面积加倍,我可以将标记大小加倍,和/或取 alpha 的平方根;和缩放相反。
请注意,所有点都具有相同的大小和 alpha。理想情况下,该解决方案适用于 plot(),但如果它只能使用 scatter() 完成,那也会有帮助。
您可以通过matplotlib事件处理实现您想要的。您必须分别捕获缩放和调整大小事件。同时考虑两者有点棘手,但并非不可能。下面是一个包含两个子图的示例,左侧是线图,右侧是散点图。图形的缩放(因子)和调整大小(fig_factor)都会根据图形大小和 x 和 y 限制中的缩放因子重新缩放点。由于定义了两个限制——一个x是y方向,一个是方向,我在这里分别使用了这两个因素的最小值。如果您希望使用更大的因子进行缩放,请将两个事件函数中的minto更改为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()
Run Code Online (Sandbox Code Playgroud)
该代码已在 Pyton 2.7 和 3.6 中使用 matplotlib 2.1.1 进行了测试。
编辑
受以下评论和此答案的启发,我创建了另一个解决方案。这里的主要思想是只使用一种类型的事件,即draw_event. 起初,这些图在缩放时没有正确更新。也ax.draw_artist()随后是fig.canvas.draw_idle()像挂答案并没有真正解决问题(然而,这可能是平台/后端特定的)。相反,我fig.canvas.draw()在缩放发生变化时添加了一个额外的调用(该if语句可防止无限循环)。
此外,请避免使用所有全局变量,我将所有内容都包装到一个名为MarkerUpdater. 每个Axes实例都可以单独注册到MarkerUpdater实例,因此您还可以在一个图中有多个子图,其中一些已更新,有些未更新。我还修复了另一个错误,其中散点图中的点缩放错误——它们应该缩放二次,而不是线性(见这里)。
最后,由于之前的解决方案中缺少它,我还添加alpha了对标记值的更新。这不像标记大小那么直接,因为alpha值不能大于 1.0。出于这个原因,在我的实现中,该alpha值只能从原始值减少。在这里我实现了它,alpha当图形尺寸减小时减小。请注意,如果未alpha向 plot 命令提供值,则艺术家将存储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实例的图形尺寸和轴在添加时的限制add_ax。在 a 上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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1886 次 |
| 最近记录: |