MoYaman
MoYaman

Reputation: 11

How can i plot a list of lists with the x and y values as floats

list = [[1134.801, 1339.5333333333333],
 [1135.125, 349.6666666666667],
 [1135.582, 1374.5333333333333],
 [1136.055, 350.3333333333333],
 [1136.505, 1360.0],
 [1136.932, 360.1333333333333],
 [1137.304, 1358.2666666666667],
 [1137.814, 331.4],
 [1138.192, 1391.8],
 [1138.653, 385.6],
 [1139.055, 1391.2666666666667],
 [1139.512, 380.26666666666665],
 [1139.972, 1351.0],
 [1140.411, 342.8],
 1140.814,
 1340.7333333333333]

I have this list of lists and have been trying to plot the values in the list so that the first value in the sublists is x and the second value in the sublists is y.

    time = [i[0] for i in list]
    values = [i[1] for i in list]
    plot(time, value, marker="o", color="blue", markeredgecolor="black")
    show()

I got this error

TypeError: 'float' object is not subscriptable

I tried a couple of different approaches from StackOverflow but received the same error.

Can anyone help me or point me in the right direction to how I can keep the float values for x and y and be able to generate a plot.

Thank you

Upvotes: 1

Views: 891

Answers (1)

Esi
Esi

Reputation: 487

First of all, it seems that you did not copy the list correctly; some brackets for last two elements are missing. Second, please rename the list; the word list is already reserved by python for list data structure. Then, you can convert the list to a numpy array an plot it:

import numpy as np
import matplotlib.pyplot as plt

my_list = [[1134.801, 1339.5333333333333], [1135.125, 349.6666666666667], [1135.582,1374.5333333333333], [1136.055, 350.3333333333333], [1136.505, 1360.0],
[1136.932, 360.1333333333333], [1137.304, 1358.2666666666667],
[1137.814, 331.4], [1138.192, 1391.8],
[1138.653, 385.6], [1139.055, 1391.2666666666667],
[1139.512, 380.26666666666665], [1139.972, 1351.0],
[1140.411, 342.8], [1140.814, 1340.7333333333333]]

data = np.asarray(my_list)
plt.plot(data[:,0], data[:, 1])

Upvotes: 1

Related Questions