在轴之间移动集合

unu*_*tbu 6 python matplotlib

在使用ImportanceOfBeingErnest 的代码在轴之间移动艺术家时,我认为将它扩展到集合(例如由PathCollections生成plt.scatter)也很容易。没有这样的运气:

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()
Run Code Online (Sandbox Code Playgroud)

产量

在此处输入图片说明

删除artist.set_transform(ax.transData)(至少在调用 时ax.add_collection)似乎有点帮助,但请注意 y 偏移量仍然关闭: 在此处输入图片说明 如何正确地将集合从一个轴移动到另一个轴?

Imp*_*est 3

分散有一个 IdentityTransform 作为主变换。数据变换是内部偏移变换。因此,需要单独处理散射。

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) 
Run Code Online (Sandbox Code Playgroud)

不幸的是,没有一种set_offset_transform方法可以需要替换._transOffset属性来设置偏移变换。

在此输入图像描述