如何在Matplotlib中绘制嵌套列表为多条独立折线?
解决Matplotlib绘制嵌套坐标列表为多条折线的问题
你的数据是三层嵌套结构:最外层列表的每个元素对应一条折线,每个折线元素是由[x, y]坐标点组成的列表。之前参考的代码之所以失效,是因为它针对的是两层嵌套(比如子列表直接是y值序列),和你的数据结构不匹配。
直接用以下代码即可实现需求:
import matplotlib.pyplot as plt # 你的原始数据 data = [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [5, 7], [0, 0]], [[0, 0], [8, 8], [0, 0]], [[0, 0], [8, 8], [0, 0]], [[0, 0], [16, 5], [0, 0]], [[0, 0], [20, 9], [0, 0]], [[0, 0], [4, 8], [20, 9], [16, 5], [0, 0]], [[0, 0], [10, 11], [0, 0]]] plt.figure(figsize=(8, 6)) # 遍历每条折线的数据 for idx, line_points in enumerate(data): # 拆分x和y坐标:从每个点中提取x和y值 x_coords = [point[0] for point in line_points] y_coords = [point[1] for point in line_points] # 绘制折线,用索引作为标签区分不同折线 plt.plot(x_coords, y_coords, label=f'Line {idx+1}') # 添加图表元素 plt.xlabel('X Axis') plt.ylabel('Y Axis') plt.title('Multiple Lines from Nested Coordinate List') plt.legend(loc='upper right') plt.grid(True) # 显示图形 plt.show()
关键说明:
- 核心逻辑是拆分坐标:对每条折线的点集,通过列表推导式分别提取所有x和y值,转换成Matplotlib
plot()函数需要的一维序列。 - 对于全是
[0,0]的子列表,绘制后会显示为原点的一个点(因为所有坐标都重合),如果不需要可以提前过滤:# 过滤掉全为[0,0]的折线 filtered_data = [line for line in data if not all(p == [0,0] for p in line)]
内容的提问来源于stack exchange,提问作者DKANN01
相关产品推荐
相关产品推荐

