rh1990
rh1990

Reputation: 940

Plotting shapes in Matplotlib through a loop

plotting beginner here...

I'm trying to get Matplotlib to add circles to a figure in a loop such that it runs 'N' times. N is given by user input and for my application likely won't exceed 10.

The radii and x-coordinates of the circles are generated in a previous function. I only want them to lie on a line, so there are no y-coords. In the end I'll end up with a horizontal row of circles of varying sizes.

I'd like a loop that adds each circle to a figure, some psuedo code of what I have in mind below:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

N = input('how many circles: ')

circle_list = []
circle = []

circle_size = [1,2,3]
circle_x = [1,2,3]

for i in range N:
    circle_list[i] = [circle_size[i],circle_x[i]]
    circle[i] = plt.Circle((circle_x[i],0), circle_size[i])
    ax.add_artist(circle[i])

The second to last line is what's confusing me, I'm struggling to write a command that takes the circle size and coords, and adds plt objects 'N' times. I think I might need two loops to run through circle_list but I'm not sure.

I've explicitly written this script for 3 circles to test the coords and sizes are working ok, but now I'd like it in a loop.

Any help is appreciated!

Upvotes: 0

Views: 2184

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

The pseudocode is already quite good. There is no need for a list. Just loop up till N and each time add the circle to the axes.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6,2))
ax.set_aspect("equal")
N = 10

circle_list = []
circle = []

circle_size = np.random.rand(N)/5.+0.1
circle_x = np.arange(N)+1

for i in range(N):
    c = plt.Circle((circle_x[i],0), circle_size[i])
    ax.add_artist(c)

plt.xlim([0,N+1])
plt.ylim([-1,1])

plt.savefig(__file__+".png")    
plt.show()

enter image description here

Upvotes: 1

rh1990
rh1990

Reputation: 940

I had a friend in the office help me, here's our solution

for i, c in zip(xrange(len(circle_x)), color_lst):
    circle = plt.Circle((circle_x[i], 0), circle_size[i], color=c, alpha=0.9)
    ax.add_artist(circle)

We also added a different colour for each one, so you need a list of colours too.

Upvotes: 0

Related Questions