How do I plot a series of points in lines in matplotlib?

I am using matplotlib and Python 2.7

I have an MxN matrix of tuples, x-coordinate and velocity. How do I plot M lines of points with N points in each line with the specified x-coordinates? Preferably with the first row up?

I've tried various examples from the documentation, but to be honest I haven't found anything.

Here is an example I want to follow, t-coordinate goes from 0 to M, x range is fixed size. The points are placed on a horizontal line according to their values. Is it a little readable? Plot mockup

+3


source to share


2 answers


It looks like you have something like this:

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

Edit:

@EMS is absolutely right, I missed a rather key point of your question.



However, if you have nested lists of tuples, just convert them to an array. This will be a 3D array that you can slice as you need for x-position and speed. There is absolutely no need to generate a second dataset, and matplotlib will convert whatever you enter into it into a numpy array, no matter if there is a performance penalty.

eg.

import numpy as np

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

data = np.array(data)

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

      

This gives:

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

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

      

+5


source


Here is a Python script that makes fake data that should look like yours.

import numpy as np
import matplotlib.pyplot as plt


num_rows = 7
num_cols = 10

# Make a fake data array that 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()

      



The points you want are displayed here: plot as requested

+3


source







All Articles