Plotting histogram from dictionary Python
Question: I have a dictionary with one value associated to each key.

I would like to plot this dictionary as a bar chart with `matplotlib`, set a
different color for each bar, and find a way to use long strings as legible
labels.

    
    
    X = np.arange(len(dictionay))
    pl.bar(X, dictionay.values(), align='center', width=0.5)
    pl.xticks(X, dictionay.keys())
    pl.xticks(rotation=20)
    ymax = max(dictionay.values()) + 1
    pl.ylim(0, ymax)
    pl.show()
    

The result:

![Ugly graph showing undesired behavior](http://i.stack.imgur.com/QbuRU.png)

My keys are very long so we don't see anything clearly! And in addition it
would be great to have this plot sorted by y values. I know a dictionary can't
be sorted so may I go through a list?

Any ideas?

Thanks


Answer: > I would like to plot this dictionnay with matplotlib, set a different color
> for each key and find a way to plot the key which is a long string ... And
> in addition it would be great to have this plot sorted.

Unfortunately the best way I was able to graph long strings was to truncate
them. I arbitrarily chose 15 characters as the maximum length, you can use any
length you find appropriate.

The following code defines a dictionary (`Dictionary`), creates a list of
sorted keys and sorted values by value from largest to smallest, and truncates
keys that are too long to display well. When the bar plot is graphed, it is
done one bar at a time so it can set an individual color to the bar. The color
is chosen by iterating through the tuple defined at the beginning (Colors).

    
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    Dictionary = {"A":3,"C":5,"B":2,"D":3,"E":4,
                  "A very long key that will be truncated when it is graphed":1}
    Dictionary_Length = len(Dictionary)
    Max_Key_Length = 15
    Sorted_Dict_Values = sorted(Dictionary.values(), reverse=True)
    Sorted_Dict_Keys = sorted(Dictionary, key=Dictionary.get, reverse=True)
    for i in range(0,Dictionary_Length):
        Key = Sorted_Dict_Keys[i]
        Key = Key[:Max_Key_Length]
        Sorted_Dict_Keys[i] = Key
    X = np.arange(Dictionary_Length)
    Colors = ('b','g','r','c')  # blue, green, red, cyan
    
    Figure = plt.figure()
    Axis = Figure.add_subplot(1,1,1)
    for i in range(0,Dictionary_Length):
        Axis.bar(X[i], Sorted_Dict_Values[i], align='center',width=0.5, color=Colors[i%len(Colors)])
    
    Axis.set_xticks(X)
    xtickNames = Axis.set_xticklabels(Sorted_Dict_Keys)
    plt.setp(Sorted_Dict_Keys)
    plt.xticks(rotation=20)
    ymax = max(Sorted_Dict_Values) + 1
    plt.ylim(0,ymax)
    
    plt.show()
    

Output graph:

![Output Graph](http://i.stack.imgur.com/FynRj.png)

