如何在matplotlib.pyplot中散布一个x数据与几个不相等的y数据图

时间:2016-01-11 21:26:44

标签: python matplotlib plot tuples

基本上我有不同长度的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)

谢谢

1 个答案:

答案 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)

enter image description here

注意:您可以使用itertools.chain.from_iterable()that问题制作展平列表,这是更快的