kk96kk
kk96kk

Reputation: 55

plot list values against the list index

I have a list of list in which each list contains some numbers, let's say

t = [[5,6,1],[4,6,33],[6,33,5,10],[1,2],[1,22,44,3]]

using python3 I would like to plot each list values against this particular list index, in the above example I should have x-axis from 1 to 3, y-axis from 1 to 50 with a mark on (1,5),(1,6),(1,1),(2,4),(2,6) ...

here is my code

x = list(range(3))
y = [[5,6,1],[4,6,33],[6,33,5,10],[1,2],[1,22,44,3]]


for i in range(len(x)):
    purchases = y[i]
    for j in range(len(purchases)):
        plt.scatter(x,purchases)

it plots the first two indices correctly then i get the error:

x and y must be in the same size

output image

what is the correct way to do this?

Upvotes: 1

Views: 8662

Answers (1)

rafaelc
rafaelc

Reputation: 59274

I think you need

y = [[5,6,1],[4,6,33],[6,33,5,10],[1,2],[1,22,44,3]]


for v in y:
    plt.scatter(range(len(v)),v)

which is basically to calculate the range of each value on the go, because your y list has different-sized lists inside it

enter image description here


If you want to set the same x for each index of y , then do

for i,v in enumerate(y):
    plt.scatter([i+1]*(len(v)),v)

Notice that I've done [i+1] because the way you wrote it, seemed you wanted an index starting from 1

enter image description here

Upvotes: 8

Related Questions