基本上我有不同长度的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)
谢谢
答案 0 :(得分:1)
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问题制作展平列表,这是更快的