在轴之间移动集合 [英] Moving Collections between axes

查看:38
本文介绍了在轴之间移动集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用

删除 artist.set_transform(ax.transData)(至少在调用 ax.add_collection 时)似乎有所帮助,但请注意y偏移仍然离开:一个人如何正确地将集合从一个轴移动到另一个轴?

解决方案

散点图具有IdentityTransform作为主变换.数据变换是内部偏移变换.因此,需要单独处理散点.

来自matplotlib.collections的

 导入PathCollection从 matplotlib.transforms 导入 IdentityTransform#...如果type(artist)== PathCollection:Artist.set_transform(IdentityTransform())artist._transOffset = ax.transData别的:艺术家.set_transform(ax.transData)

不幸的是,没有 set_offset_transform 方法,因此需要替换

While playing with ImportanceOfBeingErnest's code to move artists between axes, I thought it would easy to extend it to collections (such as PathCollections generated by plt.scatter) as well. No such luck:

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

x = np.linspace(-3, 3, 100)
y = np.exp(-x**2/2)/np.sqrt(2*np.pi)
a = np.random.normal(size=10000)

fig, ax = plt.subplots()
ax.scatter(x, y)

pickle.dump(fig, open("/tmp/figA.pickle", "wb"))
# plt.show()

fig, ax = plt.subplots()
ax.hist(a, bins=20, density=True, ec="k")

pickle.dump(fig, open("/tmp/figB.pickle", "wb"))
# plt.show()

plt.close("all")

# Now unpickle the figures and create a new figure
#    then add artists to this new figure

figA = pickle.load(open("/tmp/figA.pickle", "rb"))
figB = pickle.load(open("/tmp/figB.pickle", "rb"))

fig, ax = plt.subplots()

for figO in [figA, figB]:
    lists = [figO.axes[0].lines, figO.axes[0].patches, figO.axes[0].collections]
    addfunc = [ax.add_line, ax.add_patch, ax.add_collection]
    for lis, func in zip(lists, addfunc):
        for artist in lis[:]:
            artist.remove()
            artist.axes = ax
            # artist.set_transform(ax.transData) 
            artist.figure = fig
            func(artist)

ax.relim()
ax.autoscale_view()

plt.close(figA)
plt.close(figB)
plt.show()

yields

Removing artist.set_transform(ax.transData) (at least when calling ax.add_collection) seems to help a little, but notice that the y-offset is still off: How does one properly move collections from one axes to another?

解决方案

The scatter has an IdentityTransform as master transform. The data transform is the internal offset transform. One would hence need to treat the scatter separately.

from matplotlib.collections import PathCollection
from matplotlib.transforms import IdentityTransform

# ...

if type(artist) == PathCollection:
    artist.set_transform(IdentityTransform())
    artist._transOffset = ax.transData
else:
    artist.set_transform(ax.transData) 

Unfortunately, there is no set_offset_transform method, such that one needs to replace the ._transOffset attribute to set the offset transform.

这篇关于在轴之间移动集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆