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?
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.
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.
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.
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.
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With