【问题标题】:Copy matplotlib artist复制 matplotlib 艺术家
【发布时间】:2017-02-19 21:58:08
【问题描述】:

我用 matplotlib 创建了一个 Line2D 对象数组,我想在各种绘图中使用它。但是,在多个情节中使用同一个艺术家不起作用,因为我得到了:

RuntimeError: Can not put single artist in more than one figure

我发现,艺术家一旦依附在一个轴上,就不能再依附于另一个轴了。 好吧,我的想法是简单地复制包含行的数组 copy() 但它不起作用。复制的数组仍然引用相同的对象。我想,那是因为你根本无法复制艺术家(?)。

有什么方法可以避免重新计算 Line2D 并且只需要计算一次?

【问题讨论】:

  • 您能否详细说明为什么要避免多次构建同一个艺术家?由于可以使用很少的额外代码(例如循环的一行)并且它消耗相同的内存,我不明白为什么要这样做。有关原因的更多信息应该有助于找到该问题的良好答案。
  • 如果我必须一遍又一遍地创建这些对象,它如何消耗相同的内存?(我最终得到了很多对象,不是吗?)这也与计算工作有关,目前大量参数进入计算这些线的确切位置。它要么必须每次都重新计算,要么我必须同时将数据存储在辅助数组中。
  • 无论您是创建这些对象还是复制它们……最终都会得到相同数量的对象,占用相同数量的内存。如果这都是关于计算工作的,您可以计算一次数据,然后从相同的数据创建多个 Matplotlib 对象。
  • 当然,我很困惑,仍然在比较不必做任何形式的复制。嗯,好像已经完成了

标签: python python-3.x matplotlib copy


【解决方案1】:

我非常希望在matplotlibs 的Artist Class 中有一个copy 方法!

也许,有人想将下面的代码改编成Artist Class,以便有一种transfer 方法将一个Artist 对象复制到另一个对象中。

走错路了

对包copy 中的对象使用标准copy 或deepcopy 函数不起作用。

例如,编写脚本是没有用的:

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

x = np.linspace(0, 2*np.pi, 100)

fig  = plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)

# create a Line2D object
line1, = ax1.plot(x, np.sin(x))

# copy the Line2D object 
line2 = copy.deepcopy(line1) #ERROR!

解决方案:

因此,我发现复制Artist 对象的唯一方法是创建所需类型的空对象,然后通过循环将原始对象中的所有必要属性转移到新创建的对象中。

将属性值从一个对象传输到另一个对象的工具是我定义的这个函数:

# -- Function to attributes copy
#It copies the attributes given in attr_list (a sequence of the attributes names as
#  strings) from the object 'obj1' into the object 'obj2'
#It should work for any objects as long as the attributes are accessible by
# 'get_attribute' and 'set_attribute' methods.

def copy_attributes(obj2, obj1, attr_list):
        for i_attribute  in attr_list:
            getattr(obj2, 'set_' + i_attribute)( getattr(obj1, 'get_' + i_attribute)() )

在这个函数中最重要的参数是attr_list。这是我们要从obj1 复制到obj2 的属性名称列表,例如,对于Artist.Line2D 对象,它可以是attr_list = ('xdata', 'ydata', 'animated', 'antialiased', 'color', 'dash_capstyle', 'dash_joinstyle', 'drawstyle')

由于任何Artist 对象具有不同的属性,因此此传输过程的关键是生成属性名称列表以及要传输的正确属性。

有两种方法可以生成属性名称列表:

  • 第一个选项:我们指定要选择的属性。也就是说,我们硬编码一个包含我们想要转移的所有属性的列表。它比第二种选择更艰巨。我们必须为每种类型的对象完全指定属性:这些通常是长列表。仅当我们只处理一种类型的 Artist 对象时,才值得推荐。

  • 第二个选项:我们指定未选择的属性。也就是说,我们用我们不想转移的属性编写一个“例外列表”,我们自动选择对象的所有可转移属性,但在我们的“例外列表”中。这是最快的选择,我们可以同时将它与不同类型的Artist 对象一起使用。

第一个选项:指定传输属性列表

我们只是写了一个赋值来定义我们想要转移的属性列表,如上所示。

此选项的缺点是它不能立即扩展到不同的Artist 对象,例如 Line2D 和 Circle。因为我们必须硬编码不同的属性名称列表,每种类型的 Artist 对象都有一个。

完整示例

我展示了 Line2D Artist 类的示例,如指定的问题中所示。

import matplotlib.pyplot as plt
import numpy as np

# -- Function to attributes copy
#It copies the attributes given in attr_list (a sequence of the attributes names as
#  strings) from the object 'obj1' into the object 'obj2'
#It should work for any objects as long as the attributes are accessible by
# 'get_attribute' and 'set_attribute' methods.
def copy_attributes(obj2, obj1, attr_list):
    for i_attribute  in attr_list:
        getattr(obj2, 'set_' + i_attribute)( getattr(obj1, 'get_' + i_attribute)() )

#Creating a figure with to axes
fig  = plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
plt.tight_layout() #Tweak to improve subplot layout

#create a Line2D object 'line1' via plot
x = np.linspace(0, 2*np.pi, 100)
line1, = ax1.plot(x, np.sin(x))

ax1.set_xlabel('line1 in ax1') #Labelling axis

#Attributes of the old Line2D object that must be copied to the new object
#It's just a strings list, you can add or take away attributes to your wishes
copied_line_attributes = ('xdata', 'ydata', 'animated', 'antialiased', 'color',  
                    'dash_capstyle', 'dash_joinstyle', 
                    'drawstyle', 'fillstyle', 'linestyle', 'linewidth',
                    'marker', 'markeredgecolor', 'markeredgewidth', 'markerfacecolor',
                    'markerfacecoloralt', 'markersize', 'markevery', 'pickradius',
                    'solid_capstyle', 'solid_joinstyle', 'visible', 'zorder')

#Creating an empty Line2D object
line2 = plt.Line2D([],[])

#Copying the list of attributes 'copied_line_attributes' of line1 into line2
copy_attributes(line2, line1, copied_line_attributes)

#Setting the new axes ax2 with the same limits as ax1
ax2.set_xlim(ax1.get_xlim())
ax2.set_ylim(ax1.get_ylim())

#Adding the copied object line2 to the new axes
ax2.add_artist(line2)

ax2.set_xlabel('line2 in ax2') #Labelling axis

plt.show()

输出

第二个选项:指定未传输属性的列表

在这种情况下,我们指定了我们不想转移的属性名称:我们创建一个exception list。我们自动收集Artist 对象的所有可转移 属性,并排除exception list 的名称。

优点是通常对于不同的Artist 对象,排除的属性是相同的短列表,因此,可以更快地编写此选项的脚本。在下面的示例中,列表短至except_attributes = ('transform', 'figure')

本例中的关键函数为list_transferable_attributes,如下图:

#Returns a list of the transferable attributes, that is the attributes having
# both a 'get' and 'set' method. But the methods in 'except_attributes' are not
# included
def list_transferable_attributes(obj, except_attributes):
    obj_methods_list = dir(obj)

    obj_get_attr = []
    obj_set_attr = []
    obj_transf_attr =[]

    for name in obj_methods_list:
        if len(name) > 4:
            prefix = name[0:4]
            if prefix == 'get_':
                obj_get_attr.append(name[4:])
            elif prefix == 'set_':
                obj_set_attr.append(name[4:])

    for attribute in obj_set_attr:
        if attribute in obj_get_attr and attribute not in except_attributes:
            obj_transf_attr.append(attribute)

    return obj_transf_attr

完整示例

import matplotlib.pyplot as plt
import numpy as np

# -- Function to copy, or rather, transfer, attributes
#It copies the attributes given in attr_list (a sequence of the attributes names as
#  strings) from the object 'obj1' into the object 'obj2'
#It should work for any objects as long as the attributes are accessible by
# 'get_attribute' and 'set_attribute' methods.
def copy_attributes(obj2, obj1, attr_list):
    for i_attribute  in attr_list:
        getattr(obj2, 
                'set_' + i_attribute)( getattr(obj1, 'get_' + i_attribute)() )

# #Returns a list of pairs (attribute string, attribute value) of the given 
# # attributes list 'attr_list' of the given object 'obj'                
# def get_attributes(obj, attr_list):
#     attr_val_list = []
#     for i_attribute  in attr_list:
#         i_val = getattr(obj, 'get_' + i_attribute)()
#         attr_val_list.append((i_attribute, i_val))
#     
#     return attr_val_list

#Returns a list of the transferable attributes, that is the attributes having
# both a 'get' and 'set' method. But the methods in 'except_attributes' are not
# included
def list_transferable_attributes(obj, except_attributes):
    obj_methods_list = dir(obj)

    obj_get_attr = []
    obj_set_attr = []
    obj_transf_attr =[]

    for name in obj_methods_list:
        if len(name) > 4:
            prefix = name[0:4]
            if prefix == 'get_':
                obj_get_attr.append(name[4:])
            elif prefix == 'set_':
                obj_set_attr.append(name[4:])

    for attribute in obj_set_attr:
        if attribute in obj_get_attr and attribute not in except_attributes:
            obj_transf_attr.append(attribute)

    return obj_transf_attr


#Creating a figure with to axes
fig  = plt.figure()
ax1 = plt.subplot(211) #First axes
ax2 = plt.subplot(212) #Second axes
plt.tight_layout() #Optional: Tweak to improve subplot layout

#create an artist Line2D object 'line1' via plot
x = np.linspace(0, 2*np.pi, 100)
line1, = ax1.plot(x, np.sin(x))

#create an artist Circle object
circle1 = plt.Circle([1,0], 0.5, facecolor='yellow', edgecolor='k')
#Adding the object to the first axes
ax1.add_patch(circle1)

#Labelling first axis
ax1.set_xlabel('line1 and circle1 in ax1') 

#Methods that we should not copy from artist to artist
except_attributes = ('transform', 'figure')

#Obtaining the names of line2D attributes that can be transfered 
transferred_line_attributes = list_transferable_attributes(line1, except_attributes)

#Obtaining the names of Circle attributes that can be transfered
transferred_circle_attributes = list_transferable_attributes(circle1, except_attributes)

#Creating an empty Line2D object
line2 = plt.Line2D([],[])
circle2 = plt.Circle([],[])

#Copying the list of attributes 'transferred_line_attributes' of line1 into line2
copy_attributes(line2, line1, transferred_line_attributes)
copy_attributes(circle2, circle1, transferred_circle_attributes)

#attr_val_list_line2 = get_attributes(line2, line1_attr_list)

#Setting the new axes ax2 with the same limits as ax1
ax2.set_xlim(ax1.get_xlim())
ax2.set_ylim(ax1.get_ylim())

#Adding the copied object line2 to the new axes
ax2.add_line(line2) #.add_artist(line2) also possible
ax2.add_patch(circle2) #.add_artist(circle2) also possible

ax2.set_xlabel('line2 and circle2 in ax2') #Labelling axis

plt.show()

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多