How can I plot many thousands of circles quickly?

后端 未结 4 568
耶瑟儿~
耶瑟儿~ 2021-02-09 00:08

I\'m trying to plot several (many thousands) of circle objects - I don\'t have much experience working with python. I\'m interested in specifying the position, radius and color

4条回答
  •  春和景丽
    2021-02-09 00:32

    You would certainly want to move ...gca() outside of your loop. You can also use list comprehension.

    fig = plt.figure()
    ax = plt.gcf().gca()
    
    [ax.add_artist(plt.Circle((xvals[q],yvals[q]),rvals[q],color=[0,0,0])) 
     for q in xrange(4)]  # range(4) for Python3
    

    Below are some tests to generate 4,000 circles using the various methods:

    xvals = [0,.1,.2,.3] * 1000
    yvals = [0,.1,.2,.3] * 1000
    rvals = [0,.1,.1,.1] * 1000
    
    %%timeit -n5 fig = plt.figure(); ax = plt.gcf().gca()
    for q in range(4000):
        circle1=plt.Circle((xvals[q], yvals[q]), rvals[q], color=[0,0,0])
        plt.gcf().gca().add_artist(circle1)
    5 loops, best of 3: 792 ms per loop
    
    %%timeit -n5 fig = plt.figure(); ax = plt.gcf().gca()
    for q in xrange(4000):
        ax.add_artist(plt.Circle((xvals[q],yvals[q]),rvals[q],color=[0,0,0]))
    5 loops, best of 3: 779 ms per loop
    
    %%timeit -n5 fig = plt.figure(); ax = plt.gcf().gca()
    [ax.add_artist(plt.Circle((xvals[q],yvals[q]),rvals[q],color=[0,0,0])) for q in xrange(4000)]
    5 loops, best of 3: 730 ms per loop
    

提交回复
热议问题