kdubs kdubs - 1 year ago 247
Python Question

Python Histogram Plotting with Strings

I am trying to create a histogram plot of some monthly sales data. I have the data available as an ordered dictionary that looks like this

sales_dict = collections.OrderedDict([('Jan', 0), ('Feb', 0), ('Mar', 0), ('Apr', 0), ('May', 0), ('Jun', 0), ('Jul', 0), ('Aug', 11), ('Sept', 2), ('Oct', 2), ('Nov', 0), ('Dec', 0)])

I have tried using pyplot and pylab with no success. I want my histogram to have the month names on the x-axis and the number of sales as the y-axis. I have tried:

import pylab
from random import randint

fig_num = randint(1,10000)



import matplotlib.pyplot as plt

val, weight = zip(*[(k, v) for k,v in sales_dict.items()])


in both cases I get the error: "weights should have the same shape as x". I am unfamiliar with most of python's plotting tools, but I am wondering if it is because the keys in my dictionary are strings and not numbers? Any clarification would be appreciated!

jme jme
Answer Source

I don't know that plt.hist is the right function to use here. Rather, I'd use plt.bar with the tick_labels parameter to label the plot with the months:

centers = range(len(sales))
plt.bar(centers, sales.values(), align='center', tick_label=sales.keys())
plt.xlim([0, 11])

This gives:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download