【问题标题】:Plot table values from SQL (MariaDB) with matplotlib使用 matplotlib 从 SQL (MariaDB) 绘制表值
【发布时间】: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 &lt;module&gt; 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


【解决方案1】:

不要将对象分配给execute() 调用,而只是迭代分配的游标对象:

cur = mariadb_connection.cursor()
cur.execute("SELECT time, voltage FROM sensortable")

data = []
xTickMarks = []

for row in cur.fetchall():
    data.append(int(row[1]))
    xTickMarks.append(str(row[0]))

【讨论】:

  • 进行更改后出现另一个错误:Traceback (most recent call last): File "plot_script.py", line 23, in &lt;module&gt; data.append(int(row[1])) TypeError: int() argument must be a string or a number, not 'NoneType'
  • 查看使用 fetchall 的更新,将对象名称更改为 cur 以避免命名与实际方法发生冲突。
  • 使用上面建议的更改更新了我的代码。错误仍然显示:Traceback (most recent call last): File "plot_script.py", line 23, in &lt;module&gt; data.append(int(row[1])) TypeError: int() argument must be a string or a number, not 'NoneType'
  • 我还用另一个测试脚本确认了结果是否是从这个 python 脚本的更精简版本的数据库中提取的。这是我的终端输出:pi@raspberrypi:~/projects $ python test_select.py 10:28, 5964.00 10:29, 6092.00 10:30, 6407.00 10:39, 2251.00 10:40, 2489.00 10:41, 8927.00 10:42, 6146.00 10:43, 8172.00 10:44, 8053.00 10:45, 7720.00 10:46, 7107.00 10:47, 6833.00 10:48, 8949.00 10:49, 8905.00 10:50, 8923.00 (and more data printed in two columns.....)
  • 你在树莓派上安装了 MarieDB!很有意思。 test_select.py 中有什么可以像这样获取数据?在上面的脚本中使用该实现。
猜你喜欢
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 2014-09-15
  • 2017-12-13
  • 2021-07-22
  • 1970-01-01
相关资源
最近更新 更多