Matplotlib条形图x轴不会绘制字符串值 [英] Matplotlib bar graph x axis won't plot string values

查看:257
本文介绍了Matplotlib条形图x轴不会绘制字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我叫David,我在佛罗里达州的一辆救护车上工作.

My name is David and I work for an ambulance service in Florida.

我正在使用Python 2.7和matplotlib.我正在尝试进入我的救护车呼叫数据库,并计算每个工作日发生的呼叫次数.

I am using Python 2.7 and matplotlib. I am attempting to reach into my database of ambulance calls and count up the number of calls that happen on each weekday.

然后,我将使用matplotlib创建此信息的条形图,以为医护人员提供他们每天的忙碌状况的可视化图形.

I will then use matplotlib to create a bar chart of this information to give the paramedics a visual graphic of how busy they are on each day.

这里的代码工作得很好:

HERE IS CODE THAT WORKS VERY WELL:

import pyodbc
import matplotlib.pyplot as plt
MySQLQuery = """
SELECT 
 DATEPART(WEEKDAY, IIU_tDispatch)AS [DayOfWeekOfCall]
, COUNT(DATEPART(WeekDay, IIU_tDispatch)) AS [DispatchesOnThisWeekday]
FROM AmbulanceIncidents
GROUP BY DATEPART(WEEKDAY, IIU_tDispatch)
ORDER BY DATEPART(WEEKDAY, IIU_tDispatch)
"""
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyServer;DATABASE=MyDatabase;UID=MyUserID;PWD=MyPassword')
cursor = cnxn.cursor()
GraphCursor = cnxn.cursor()
cursor.execute(MySQLQuery)

#generate a graph to display the data
data = GraphCursor.fetchall()
DayOfWeekOfCall, DispatchesOnThisWeekday = zip(*data)
plt.bar(DayOfWeekOfCall, DispatchesOnThisWeekday)
plt.grid()
plt.title('Dispatches by Day of Week')
plt.xlabel('Day of Week')
plt.ylabel('Number of Dispatches')
plt.show()

上面显示的代码效果很好.它返回一个漂亮的图形,我很高兴.我只想做一个改变.

The code shown above works very well. It returns a nice looking graph and I am happy. I just want to make one change.

X轴显示整数,而不是X轴显示星期几的名称,例如"Sunday".换句话说,星期日是1,星期一是2,依此类推

Instead of the X axis showing the names of the days of the week, such as "Sunday", it shows the integer. In other words, Sunday is 1, Monday is 2, etc.

对此的解决方法是,我重写SQL查询以使用DATENAME()而不是DATEPART(). 下面显示的是我的sql代码,用于返回星期的名称(而不是整数).

My fix for this is that I rewrite my sql query to use DATENAME() instead of DATEPART(). Shown below is my sql code to return the name of the week (as opposed to an integer).

SELECT 
 DATENAME(WEEKDAY, IIU_tDispatch)AS [DayOfWeekOfCall]
, COUNT(DATENAME(WeekDay, IIU_tDispatch)) AS [DispatchesOnThisWeekday]
FROM AmbulanceIncidents
GROUP BY DATENAME(WEEKDAY, IIU_tDispatch)
ORDER BY DATENAME(WEEKDAY, IIU_tDispatch)

我的python代码中的所有其他内容都保持不变.但是,这将无法正常工作,而且我无法理解错误消息.

Everything else in my python code stays the same. However this will not work and I cannot understand the error messages.

以下是错误消息:

Traceback (most recent call last):
  File "C:\Documents and Settings\kulpandm\workspace\FiscalYearEndReport\CallVolumeByDayOfWeek.py", line 59, in 

<module>
    plt.bar(DayOfWeekOfCall, DispatchesOnThisWeekday)
  File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 2080, in bar
    ret = ax.bar(left, height, width, bottom, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 4740, in bar
    self.add_patch(r)
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 1471, in add_patch
    self._update_patch_limits(p)
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 1489, in _update_patch_limits
    xys = patch.get_patch_transform().transform(vertices)
  File "C:\Python27\lib\site-packages\matplotlib\patches.py", line 547, in get_patch_transform
    self._update_patch_transform()
  File "C:\Python27\lib\site-packages\matplotlib\patches.py", line 543, in _update_patch_transform
    bbox = transforms.Bbox.from_bounds(x, y, width, height)
  File "C:\Python27\lib\site-packages\matplotlib\transforms.py", line 745, in from_bounds
    return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
TypeError: coercing to Unicode: need string or buffer, float found

我无法弄清楚.

总而言之,当我输出数据时,x轴为代表星期几的整数,y轴代表救护车事件的计数,Matplotlib将产生一个漂亮的图形.但是当我的数据输出是x轴时,它是一个字符串(星期日,星期一等).那么Matplotlib将无法正常工作.

To sum up, when I output my data with the x axis as integers representing days of week and y axis showing a count of the number of ambulance incidents, Matplotlib will produce a nice graph. But when my data output is the x axis is a string (Sunday, Monday, etc). then Matplotlib will not work.

我已经在Google上进行了数小时的研究,并阅读了matplotlib文档. 请帮我解决一下这个.我希望使用Matplotlib作为报告引擎.

I have done several hours of research on Google and reading the matplotlib documentation. Please help me with this. I am hoping to use Matplotlib as my reports engine.

推荐答案

您的问题与SQL查询无关,它只是结束的一种方式.您真正要问的是如何在pylab中更改条形图上的文本标签. 条形图的文档对于自定义很有用,但只需

Your question has nothing to do with an SQL query, it is simply a means to end. What you are really asking is how to change the text labels on a bar chart in pylab. The docs for the bar chart are useful for customizing, but to simply change the labels here is a minimal working example (MWE):

import pylab as plt

DayOfWeekOfCall = [1,2,3]
DispatchesOnThisWeekday = [77, 32, 42]

LABELS = ["Monday", "Tuesday", "Wednesday"]

plt.bar(DayOfWeekOfCall, DispatchesOnThisWeekday, align='center')
plt.xticks(DayOfWeekOfCall, LABELS)
plt.show()

这篇关于Matplotlib条形图x轴不会绘制字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆