Question

I'm trying to plot circles in matplotlib using a file as source of data, and I'm finding some difficulties.

This is my code

with open('DataSample2.txt', 'r') as file:
    file.readline()  # skip the first line
    xy = [[float(x) for x in line.split(' ')[:2]] for line in file]
    rad = [[float(x) for x in line.split(' ')[2:3]] for line in file]

    print(xy)
    print(rad)

    #circle = plt.Circle(xy[0], rad[0], color='g')

    #fig = plt.gcf()

    #fig.gca().add_artist(circle)

    #fig.savefig('plotcircles.png')

And this is my data source:

x y rad
2 5 2
2 2 2
3 1 3
5 2 1
6 4 3

My problem, probably, is how I am creating the xy and rad lists.

Was it helpful?

Solution

I don't think you need list to plot circles.

import matplotlib.pyplot as plt
from numpy.random import rand

with open('DataSample2.txt', 'r') as f:
    next(f)
    xmin = ymin = 999999999
    xmax = ymax = -999999999
    for line in f:
        x, y, r = map(float, line.split())
        circle = plt.Circle((x, y), r, color=rand(3))
        fig = plt.gcf()
        fig.gca().add_artist(circle)
        xmin = min(x-r, xmin)
        xmax = max(x+r, xmax)
        ymin = min(y-r, ymin)
        ymax = max(y+r, ymax)
        #break # if you want draw only one circle, break here.
    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)
    plt.show()

enter image description here

OTHER TIPS

Probably something like this is better:

all_xy = []
all_rad = []

with open('DataSample2.txt', 'r') as file:
    file.readline()  # skip the first line
    for line in file:
        vals = line.split()
        all_xy.append([float(x) for x in vals[:2]])
        all_rad.append(float(vals[-1]))


print(all_xy)
print(all_rad)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top