如何在matplotlib中的行上绘制一系列点?

时间:2012-03-19 21:56:10

标签: python matplotlib

我正在使用matplotlib和Python 2.7

我有一个MxN矩阵的元组,一个x坐标和一个速度。如何绘制M行的点,在指定的x坐标系的每一行中有N个点?最好是第一排在顶部?

我已经尝试过文档中的各种示例,但说实话,我还没有真正找到任何内容。

以下是我想要完成的一个粗略示例,t坐标从0到M,x范围具有固定大小。根据它们的值将点放置在水平线中。它有点可读吗? Plot mockup

2 个答案:

答案 0 :(得分:5)

听起来你有这样的事情:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.random((10, 20))
x = x.cumsum(axis=1)

fig, ax = plt.subplots()
for i, row in enumerate(x):
    ax.plot(row, i * np.ones_like(row), 'ko')

ax.set_ylim([-0.5, 9.5])
ax.set_yticks(range(10))
ax.invert_yaxis()
plt.show()

enter image description here

修改:

@EMS是对的,我错过了你问题的一个重点。

但是,如果您有嵌套的元组列表,只需将其转换为数组即可。它将是一个3D数组,您可以根据需要切割x位置和速度。绝对不需要生成第二个数据集,matplotlib会将您输入的任何内容转换为numpy数组,因此不存在性能损失。

E.g。

import numpy as np

data = [[(1, 2), (3, 4)],
        [(5, 6), (7, 8)]]

data = np.array(data)

x = data[:,:,0]
velocity = data[:,:,1]

这会产生:

x: 
array([[1, 3],
       [5, 7]])

velocity:
array([[2, 4],
       [6, 8]])

答案 1 :(得分:3)

这是一个Python脚本,它可以使虚假数据与您的数据类似。

import numpy as np
import matplotlib.pyplot as plt


num_rows = 7
num_cols = 10

# Make a fake data array that's just a list of lists.
# And each list has num_cols number of different tuples.
# The x-data is assumed to be the first coordinate of the
# tuple

my_data = []
for ii in range(num_rows):
    my_data.append([])
    for jj in range(num_cols):
        my_data[ii].append( (24*np.random.rand(),np.random.rand()) )


# Now plot the different rows as separate plots.
fig = plt.figure()
ax = fig.add_subplot(111)
for ii in range(num_rows):

    # The y-axis values are just a constant based on the current row.
    cur_tvals = [ii]*num_cols

    # The x values are gotten by using a list comprehension to
    # grab just the first tuple element. 
    cur_xvals = [tup[0] for tup in my_data[ii]]

    # Add the current curve to the plot. Specifying '.' as the
    # symbol get rid of any lines connecting the markers.
    ax.plot(cur_xvals,cur_tvals,'.',markersize=5)

# Setting axes based on num_rows
ax.set_ylim([-0.5, num_rows-1+0.5])
ax.set_yticks(range(num_rows))
ax.invert_yaxis()
plt.show()

这可以根据需要绘制点: plot as requested