开发者社区> 问答> 正文

Pandas DataFrame,matplotlib和不同的SQL数据类型

我想从MySQL数据库创建温度和时间数据图。使用matplotlib和pandas使用python3on raspbian我试图在Y轴上插入温度,在X轴上插入时间。

Y轴工作正常,它绘制temps(float)没有任何问题。但是,当我尝试添加time(time)时,它会输出我假设的错误数据,因为它具有不同的数据类型。如果我使用其他列,如ID(int),那么它的工作原理。我不确定是否需要将时间转换为字符串或者是否有其他方法。

答案可能在于Pandas中列的更改数据类型看似相似,但由于我从MySQL插入数据,我不确定如何将其应用于我自己的问题。
import matplotlib.pyplot as plt
import pandas as pd
import MySQLdb

def mysql_select_all():

conn = MySQLdb.connect(host='localhost',
                       user='user',
                       passwd='password',
                       db='database')
cursor = conn.cursor()
sql = "SELECT time,temperature FROM table ORDER BY time DESC LIMIT 288"
cursor.execute(sql)
result = cursor.fetchall()
df = pd.DataFrame(list(result),columns=["time","temperature"])
x = df.time
y = df.temperature
plt.title("Temperature Data from Previous 24 Hours", fontsize="20")
plt.plot(x, y)
plt.xlabel("Time")
plt.ylabel("Temperature (\u2103)")
plt.tick_params(axis='both',which='major',labelsize=14)
plt.savefig('test.png')
cursor.close()

print("Start")

mysql_select_all()

print("End")
上面的代码目前输出下面的图像。
yJInG

展开
收起
一码平川MACHEL 2019-01-22 14:59:07 2596 0
1 条回答
写回答
取消 提交回答
  • 最好以这种方式导入日期:

    from matplotlib.dates import (YEARLY, DateFormatter,

                              rrulewrapper, RRuleLocator, drange)

    然后使用

    plt.plot_date(x,y)
    如果你需要转换它只需使用:

    matplotlib.dates.date2num(x)

    2019-07-17 23:26:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server在电子商务中的应用与实践 立即下载
中文:即学即用的Pandas入门与时间序列分析 立即下载
即学即用的Pandas入门与时间序列分析 立即下载