6

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?

Dan
  • 12,157
  • 12
  • 50
  • 84
Greg Hennessy
  • 467
  • 3
  • 5
  • 17

4 Answers4

16

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()
Alvaro Fuentes
  • 16,937
  • 4
  • 56
  • 68
8

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()
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
  • This looks very promising, Counter seems to be a 2.7 feature, and I'm using 2.6 (curse you redhat 6.3!), but I'll explore this. – Greg Hennessy Dec 23 '13 at 18:28
1

You'll of course have to start by counting the elements:

>>> from collections import Counter
>>> counts = Counter(my_iterator)

Then, we wish to count these counts:

>>> count_von_count = Counter(counts.values())

Then you've got the size of your bars. Make it into a list and plot it:

>>> bars = [count_von_count[i] for i in range(max(count_von_count) + 1)]

Example for your extended list:

>>> from collections import Counter
>>> counts = Counter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1])
>>> counts
Counter({1: 2, 0: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})
>>> count_von_count = Counter(counts.values())
>>> count_von_count
Counter({1: 9, 2: 1})
>>> bars = [count_von_count[i] for i in range(max(count_von_count) + 1)]
>>> bars
[0, 9, 1]
Jaccar
  • 1,720
  • 17
  • 46
Noctua
  • 5,058
  • 1
  • 18
  • 23
0

If you collect your data into a list of lists, then you might do something like this:

import numpy as np
import matplotlib.pyplot as plt

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

count = map(len, x)
plt.bar(range(len(count)), count)
plt.show()

enter image description here

Note that the first bar has height 10, not 9. I don't know if that is what you desire or if I'm misunderstanding your intention.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677