【发布时间】:2018-06-06 04:37:32
【问题描述】:
我想提取两列数据并将它们用作值在 matplotlib 上绘制直方图。我尽可能地密切关注Matplotlib: Plot the result of an SQL query 中的这个答案,只是在几个方面有所不同(即使用的 SQL 模块)。但是,我的脚本运行时出错:
Traceback (most recent call last):
File "plot_script.py", line 22, in <module>
for row in result:
TypeError: 'NoneType' object is not iterable
我的python脚本是:
import mysql.connector as mariadb
import matplotlib as mpl
mpl.use('Agg')
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
mariadb_connection = mariadb.connect(user='user1', password='pw', database='sensordb')
cursor = mariadb_connection.cursor()
result=cursor.execute("SELECT time, voltage FROM sensortable")
#the data
data = []
xTickMarks = []
for row in result:
data.append(int(row[1]))
xTickMarks.append(str(row[0]))
mariadb_connection.close()
## necessary variables
ind = np.arange(len(data)) # the x locations for the groups
width = 0.35 # the width of the bars
## the bars
rects1 = ax.bar(ind, data, width,
color='black',
error_kw=dict(elinewidth=2,ecolor='red'))
# axes and labels
ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0,45)
ax.set_ylabel('Voltage')
ax.set_xlabel('Time')
ax.set_title('Sensor measurements')
ax.set_xticks(ind+width)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=45, fontsize=10)
plt.show()
fig.savefig('plot1.jpg')
更新:
我还打印了使用另一个 python 脚本获得的数据,以确定我从 SQL 查询中获得的数据。终端打印:Decimal('2479.00')), (u'13:15', Decimal('3182.00')), (u'13:20', Decimal('3076.00')), (u'13:25', Decimal('2795.00')), (u'13:30', Decimal('3457.00')), (u'13:35', Decimal('2515.00')), (u'13:40', Decimal('3006.00')), (u'13:45', Decimal('3618.00')), (u'13:50', Decimal('3857.00'))] (and more similar data).......)
鉴于这种“十进制”数据类型可能会导致问题,我该如何解决?
我已将我的 python 脚本的一行修改为data.append(int(float(row[1]))),但它仍然返回错误Traceback (most recent call last): File "test_select.py", line 19, in <module> data.append(int(float(row[1]))) TypeError: float() argument must be a string or a number
【问题讨论】:
-
您的 result 似乎是
None。检查您的查询是否实际返回记录,可能在 Python 之外的控制台中。 -
我已经直接在SQL程序中用
"SELECT time, voltage FROM sensortable;查询了数据库,它给我带来了预期的两列数据。152 rows in set (0.00 sec)
标签: python mysql matplotlib mariadb