4

I've got a bunch of occurances of numbers and want to plot them in a bar chart (like a histogram).

I've got the chart working, but it is in the order I typed in the values, not the order of highest to lowest, which is what I want.

Here is the code so far:

 phenos = [128, 20, 0, 144, 4, 16, 160, 136, 192, 52, 128, 20, 0, 4, 16, 144, 130, 136, 132, 22, 
128, 160, 4, 0, 32, 36, 132, 136, 164, 130, 128, 22, 4, 0, 144, 160, 54, 130, 178, 132, 
128, 4, 0, 136, 132, 68, 196, 130, 192, 8, 128, 4, 0, 20, 22, 132, 144, 192, 130, 2, 
128, 4, 0, 132, 20, 136, 144, 192, 64, 130, 128, 4, 0, 144, 132, 28, 192, 20, 16, 136, 
128, 6, 4, 134, 0, 130, 160, 132, 192, 2,  128, 4, 0, 132, 68, 160, 192, 36, 64, 
128, 4, 0, 136, 192, 8, 160, 12, 36, 128, 4, 0, 22, 20, 144, 86, 132, 82, 160,
128, 4, 0, 132, 20, 192, 144, 160, 68, 64, 128, 4, 0, 132, 160, 144, 136, 192, 68, 20]

from collections import Counter
import numpy as np
import matplotlib.pyplot as plt


labels, values = zip(*Counter(phenos).items())

indexes = np.arange(len(labels))
width = 1

plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.show()

It produces the following picture. Sorry the labels are all smushed.

I want it to go from highest to lowest... does anyone know how I can do that without changing my phenos? I tried doing

phenos.sort()

before I drew the graph but that did not change the graph. Thanks in advance!

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
jcam77
  • 173
  • 2
  • 4
  • 17
  • Why not use [`numpy.histogram`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html) with `bins=set(phenos)`? Example: http://stackoverflow.com/a/5328669/1634191 – wflynny Mar 05 '14 at 17:43

1 Answers1

6

Sort Counter(phenos).items() at first:

In [40]: from collections import Counter
    ...: import numpy as np
    ...: import matplotlib.pyplot as plt
    ...: from operator import itemgetter
    ...: 
    ...: c = Counter(phenos).items()
    ...: c.sort(key=itemgetter(1))
    ...: labels, values = zip(*c)
    ...: 
    ...: indexes = np.arange(len(labels))
    ...: width = 1
    ...: 
    ...: plt.bar(indexes, values, width)
    ...: plt.xticks(indexes + width * 0.5, labels)
    ...: plt.show()

ouput: enter image description here


Or if you wanna sort by the x-axis, just use itemgetter(0):

c.sort(key=itemgetter(0))

which gets:

enter image description here

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108