Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot the number of times each element is in a list [closed]

I'm trying to do something slightly that I wouldn't think would be hard, but I can't figure out how to get python/matplotlib/pylab to do.

Given an input, I want a histogram that shows me the number of times each element appears.

Given a list

x=range(10)

I'd like output that has a single bar, y value of 10, equal to x=1, no other graphs.

given a list

x=range(10)
x.append(1)

I'd like the output to have two bars, a y value of 9 for x=1, a y value of 1 for x=2. How can I do this?

like image 318
Greg Hennessy Avatar asked Dec 18 '13 18:12

Greg Hennessy


People also ask

How do you count the number of occurrences of an element in a list?

The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.

How do you count the number of occurrences of each element in a list in Python?

1) Using count() method count() is the in-built function by which python count occurrences in list. It is the easiest among all other methods used to count the occurrence. Count() methods take one argument, i.e., the element for which the number of occurrences is to be counted.

How do you find the occurrences of an element in a list Python?

Python Program 3 To get the occurrence of a single element, use the element as the key and display the value corresponding to it. This will be the occurrence of that element. To use the Counter() function, import it from the collections module.

How do you count maximum occurrences of an element in an array in Python?

Given a list, the task is to find the number of occurrences of the largest element of the list. Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list.


2 Answers

This code gives you a histogram like the one you like:

import matplotlib.pyplot as plt
import numpy as np
y = np.array([0,1,2,3,4,5,6,7,8,9,1])
plt.hist(y);
plt.show()
like image 173
Alvaro Fuentes Avatar answered Sep 17 '22 18:09

Alvaro Fuentes


Something like this? This code uses a Counter to count the number of instances that an object occurs in an array (in this case counting the number of times an integer is in your list).

import matplotlib.pyplot as plt
from collections import Counter

# Create your list
x = range(10)
x.append(1)

# Use a Counter to count the number of instances in x
c = Counter(x)

plt.bar(c.keys(), c.values())
plt.show()
like image 29
Ffisegydd Avatar answered Sep 20 '22 18:09

Ffisegydd