不能把单个艺术家放在一个以上的数字中

时间:2017-11-29 14:09:47

标签: matplotlib plot python-3.6

这是我的问题。

我创建了一个绘制圆圈列表的函数。 我需要先用圆圈C2绘制我的圆圈C1,然后用C3 ......直到C40。

try JSONDecoder().decode(Food.self, from: data)

现在我创建C1:

import matplotlib.pyplot as plt 
from matplotlib.patches import Circle

def plot_circle(Liste_circles):


    fig = plt.figure(figsize=(5,5))   
    ax = fig.add_subplot(111)

    # On définie un fond blanc
    ax.set_facecolor((1, 1, 1))

    ax.set_xlim(-5, 15)
    ax.set_ylim(-6, 12)    

    for c in Liste_circles:
        ax.add_patch(c)

    plt.show()

最后我尝试绘制它。
第一个情节有效:

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')

第二个失败了:

C2=Circle(xy=(6, 3), radius=4, fill=False, color='b')
plot_circle([C1,C2])

错误:

  

RuntimeError:无法将单个艺术家放在多个图中

我可以通过这样做来实现:

C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])

如何绘制圆圈C1与其他40个圆圈,而不必每次都重新创建C1? (我的程序需要花费10分钟才能通过复杂的算法创建C1,我无法在40个绘图中重新创建它......)。

2 个答案:

答案 0 :(得分:0)

以下是如何使其工作:只需复制圆圈并绘制副本:

首先导入副本:

from copy import copy
然后,而不是做:

for c in Liste_circles:
    ax.add_patch(c)

我们必须这样做:

for c in Liste_circles:
   new_c=copy(c)
   ax.add_patch(new_c)

这样我们就不会绘制同一个圆圈(=同一个艺术家),但是它的副本

答案 1 :(得分:0)

此外,如果您感兴趣,可以设置关于圆圈值的x和y轴:

import matplotlib.pyplot as plt 
from matplotlib.patches import Circle
from copy import copy


def plot_circles (Liste_circles):

    if len(Liste_circles) == 0:
        print('No circles to display')
    else:

        fig = plt.figure(figsize=(5,5))   
        ax = fig.add_subplot(111)


        # On définie un fond blanc
        ax.set_facecolor((1, 1, 1))


        # On définie les limites des axes pour que nos cercles soient au centre de notre graphique
        # --> xmin sera le plus petit des x de tous les cercles - 2 fois le plus grand des rayons
        # --> xmax sera le plus grand des x de tous les cercles + 2 fois le plus grand des rayons
        # --> ymin sera le plus petit des y de tous les cercles - 2 fois le plus grand des rayons
        # --> ymax sera le plus grand des y de tous les cercles + 2 fois le plus grand des rayons
        L_x = [c.center[0] for c in Liste_circles]
        L_y = [c.center[1] for c in Liste_circles]
        L_r = [c.radius for c in Liste_circles]

        min_x=min(L_x); max_x=max(L_x);min_y=min(L_y); max_y=max(L_y);max_r=max(L_r)

        xmin = min_x - 2*max_r
        xmax = max_x + 2*max_r

        ymin = min_y - 2*max_r
        ymax = max_y + 2*max_r

        ax.set_xlim(xmin, xmax)
        ax.set_ylim(ymin, ymax)


        for c in Liste_circles:
            new_c=copy(c)
            ax.add_patch(new_c) 

        plt.show()

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C2=Circle(xy=(6, 3), radius=4, fill=False, color='b')
C3=Circle(xy=(7, 2), radius=4, fill=False, color='r')
相关问题