matplotlib连接圆周1000个点绘图时仅显示单条线的问题求助
问题修复方案
核心错误点
- 坐标存储列表
x_coor、y_coor初始化位置错误:放在for循环内部,每次迭代都会清空历史点位,循环结束后仅保留最后一组2个x值相同的点位,绘制结果自然为竖直线。 r_count变量作用域错误:在循环内部重复赋值为1,导致每次x轴步进长度固定,点位分布不符合预期。- 点位数量变量类型错误:
point_count使用float类型接收输入不符合使用场景,应改为int类型。
修复后代码
import math import matplotlib.pyplot as plt h = float(input("Enter H value (center-x): ")) k = float(input("Enter K value (center-y): ")) r = float(input("Enter your R value (radius): ")) point_count = int(input("How many points do you want: ")) x_min = float(h - r) x_max = float(h + r) CENTER_POINT = (h, k) CENTER_X = CENTER_POINT[0] CENTER_Y = CENTER_POINT[1] # 坐标列表初始化放在循环外部 x_coor = [] y_coor = [] side = int(point_count / 2 + 1) # r_count放在循环外部,每次迭代自增 r_count = 1 for i in range(0, side): increment_segment = float(r * r_count / side) r_count += 1 x_min += increment_segment if x_min >= x_max: x_min -= increment_segment pass y_formula_positive = math.sqrt(math.pow(r, 2) - math.pow(x_min - h, 2)) + k y_formula_negative = 0 - math.sqrt(math.pow(r, 2) - math.pow(x_min - h, 2)) + k print(x_min, y_formula_positive) print(x_min, y_formula_negative) x_coor.append(x_min) x_coor.append(x_min) y_coor.append(y_formula_positive) y_coor.append(y_formula_negative) print(i) plt.plot(x_coor, y_coor) # 可选:添加等比例轴设置,避免圆被拉伸为椭圆 plt.axis('equal') plt.show()
优化建议
如果需要更均匀的圆周点位,建议使用极坐标转直角坐标的方式计算点位,避免x轴步进方式导致的弧长分布不均问题,核心逻辑如下:
for i in range(point_count): # 按角度均分圆周 rad = 2 * math.pi * i / point_count x = h + r * math.cos(rad) y = k + r * math.sin(rad) x_coor.append(x) y_coor.append(y)
内容的提问来源于stack exchange,提问作者user16208301
相关产品推荐
相关产品推荐

