我正在尝试使用文件作为数据来源在matplotlib中绘制圆圈,我发现了一些困难。
这是我的代码
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')
这是我的数据来源:
x y rad
2 5 2
2 2 2
3 1 3
5 2 1
6 4 3
我的问题可能是我如何创建xy和rad列表。
答案 0 :(得分:1)
这样的事情可能更好:
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)
答案 1 :(得分:1)
我认为你不需要列表来绘制圆圈。
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()