在matplotlib中绘制具有不同列大小数组的一维数组

2024-04-20 00:55:11 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于此,我有x&y数组,我可以很容易地绘制点,如下所示:

a = np.arange(10).reshape(5, 2)

plt.scatter(a.T[0], a.T[1])
plt.xlabel("Interval")
plt.ylabel("Value")
plt.show()

enter image description here

但目前,我有一个大小不一的列表,比如:

a = [
    [0, 1, 3],
    [4, 2],
    [1, 4, 7, 2],
    [2],
    [3, 4, 5, 6]
]

plt.scatter(a, list(range(len(a))))
plt.xlabel("Interval")
plt.ylabel("Value")
plt.show()

但是,这会产生一个错误:设置一个数组元素的序列,当维度不固定,大小不相等时(dimen)x!=(dimen)y),但我希望得到这样的结果:

enter image description here

我怎样才能得到那样的情节?你知道吗


Tags: 列表valueshownp绘制plt数组list
2条回答

您可以创建要手动打印的数据:

import numpy as np
import matplotlib.pyplot as plt

a = np.array([
    [0, 1, 3],
    [4, 2],
    [1, 4, 7, 2],
    [2],
    [3, 4, 5, 6]

])

data = np.array([[x, y] for x, ys in enumerate(a) for y in ys])

plt.scatter(data[:, 0], data[:, 1], c='red')
plt.xlabel("Interval")
plt.ylabel("Value")
plt.show()

输出enter image description here

你差一点就到了。您只需使用单for循环来绘制单个列表,如下所示。lst一次将是一个子列表 [i]*len(lst)将为该子列表生成x-datapoints的数量。你知道吗

for i, lst in enumerate(a):
    plt.scatter([i]*len(lst), lst,  color='r')
plt.xlabel("Interval")
plt.ylabel("Value")

enter image description here

相关问题 更多 >