0

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!

2
  • now convert pseudocode to real code and run it and then show us error messages. Probably it should need only append() to add elements to lists. Commented Jan 27, 2017 at 11:07
  • The following could help: matplotlib.collections.PatchCollection, there you just pass a list of patches as as parameter. Commented Jan 27, 2017 at 11:10

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Like I said, a colleague saw me writing this and offered help. But there's no harm in asking the community for a solution as it benefits me, and helps someone who has a similar question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.