Skip to main content
 首页 » 编程设计

python之如何在 matplotlib.pyplot 中散点绘制一个 x 数据与多个不相等的 y 数据图

2025年05月04日17dudu

基本上我有不同长度的 x 与 y 元组。如何在 matplotlib 中绘制以下内容?

x=[1,2,3,4] 
y=([1,1.1,1.4,0.9,0.8],[2.1,2.2,2.3],[3.1,3.3],[4.4,4.5,4.3,4.22,4.2,4.1,4.4411]) 
plt.scatter(x,y) 

谢谢

请您参考如下方法:

IIUC 你需要将你的 x 列表扩展到 y 维度,然后将获得的列表扁平化并放入 plt.scatter:

x=[1,2,3,4] 
y=([1,1.1,1.4,0.9,0.8],[2.1,2.2,2.3],[3.1,3.3],[4.4,4.5,4.3,4.22,4.2,4.1,4.4411]) 
 
w = [[x[i]] * len(y[i]) for i in range(len(y))] 
 
In [555]: w 
Out[555]: [[1, 1, 1, 1, 1], [2, 2, 2], [3, 3], [4, 4, 4, 4, 4, 4, 4]] 
 
x_to_plot = [item for sublist in w for item in sublist] 
y_to_plot = [item for sublist in y for item in sublist] 
plt.scatter(x_to_plot, y_to_plot) 

注意:您可以使用 itertools.chain.from_iterable() 从 that 生成扁平列表哪个更快的问题