kdubs kdubs - 1 month ago 21
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)

pylab.figure(fig_num)
pylab.hist(sales_dict.keys(),weights=data_dict.values(),bins=range(50))
pylab.show()


and

import matplotlib.pyplot as plt

val, weight = zip(*[(k, v) for k,v in sales_dict.items()])
plt.hist(val,weights=weight)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.title(title)
plt.grid(True)

plt.show()


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

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

Comments