简体   繁体   中英

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!

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:

在此处输入图片说明

您将要使用matplotlib的条形图函数而不是直方图函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM