0

I'm trying to create a histogram in Python, but I want the histogram to have its bars sorted by the results - i.e. I have a data set with approx. 260K lines, and the histogram is counting the number of lines for each state in the USA. I've worked out how to sort the states alphabetically but I can't work out how to have the bars listed in descending order of frequency... my code is below.

Many thanks in advance!

import matplotlib.pyplot as plt
from collections import OrderedDict
from collections import Counter

def iter_values(data, column_key):
    for row in data:
        yield(row[column_key])

state = set(iter_values(data, STATE))

def make_bar_chart(data, column_key, values, y_min, y_max): 
    c = Counter(row[column_key] for row in data)
    d = OrderedDict([(k,c[k]) if k in sorted(c) else (k,0) for k in values])
    # bars are by default width 0.8, so we'll add 0.1 to the left coordinates
    xs = [i+0.1 for i,_ in enumerate(values)]
    plt.bar(xs, d.values())
    plt.ylabel('Number of incidents')
    plt.axis([0,len(values),y_min,y_max])
    plt.title(column_key)
    plt.xticks([i + 0.5 for i, _ in enumerate(values)], values, rotation='vertical')
    plt.show()

make_bar_chart(data, STATE, sorted(state), 0, 20000)
Mr. T
  • 11,960
  • 10
  • 32
  • 54
Nic
  • 13
  • 4
  • 1
    Welcome to SO. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and edit your question. I assume this is a categorical plot (x-axis state name, y-axis some number). Please add in this case also your matplotlib version, because the versions behave slightly different. – Mr. T Sep 02 '18 at 06:21
  • Thanks Mr.T. I'm sorry that my question isn't well asked - if I could do better I would I assure you! I'm not sure how to get the matplotlib version either? The plot is x-axis state name, y-axis count of the number of times each state appears in STATE data field in the data – Nic Sep 03 '18 at 03:11
  • There is mainly a sample input missing to explain the data structure of the input and that SO users can use to test an improved version of your code. But maybe you find your solution already here: https://stackoverflow.com/q/22204648/8881141 or here: https://stackoverflow.com/q/44885933/8881141 – Mr. T Sep 03 '18 at 03:23

0 Answers0