0

I have a list of lists as follows.

import random
list_of_list=[]

for i in range(1000):
    sub_list=[random.randint(0, 10) for iter in range(10)]
    list_of_list.append(sub_list)

​ I am able to plot any single sublist of the above list of lists as follows with a hist plot.

plt.hist(list_of_list[10])

Single sublist plot

Is there anyway I can plot this whole list of list in histogram or any other similar?

2 Answers 2

2

Passing a list of lists will treat every sublist as a separate group, differentiated by color.

plt.hist(list_of_list)

Example for 3 sublists:

enter image description here

If you want, you can also flatten the sublists into a single list so they are all treated as the same batch:

import itertools
merged = list(itertools.chain(*list_of_list))
plt.hist(merged)

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

You can plot it as

plt.hist([elt for lst in list_of_list for elt in lst])

example hist

You'll note that the height of the last bin is the double of the rest. Unlike similar functions, random.randint(0, 10) generates values from 0 to 10 inclusive. Due to rounding, both 9 and 10 end up in the same bin. You can create 11 bins with plt.hist(..., bins=11).

Also note that when working with large lists of numerical data, it is always much easier and faster to employ the numpy library. It's syntax may look weird at first, but you quickly get used to it. For example to create a 1d list from your 2d list, the command would be np.array(list_of_list).ravel().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.