【问题标题】:Plotting data of a mysql database by date按日期绘制 mysql 数据库的数据
【发布时间】:2019-05-27 19:26:33
【问题描述】:

我创建了一个 mysql 数据库来保存湿度、温度和其他几个带有时间戳的数据。我可以绘制数据,但是 x 轴没有标记。

我尝试设置刻度的标签,但没有正确标记它们。无法查看保存数据的日期。日期的类型是 datetime.datetime()

result = cursor.fetchall()

for r in result:
    dates.append(r[1])
    humidity.append(r[2])
    temperature.append(r[3])
    pm25.append(r[4])
    pm10.append(r[5])


fig, ax = plt.subplots()

for tick in ax.get_xticklabels():
    tick.set_rotation(45)


ax.plot(dates, humidity, color = 'b')
ax.plot(dates, temperature, color = 'r')
ax.plot(dates, pm25, color = 'orange')
ax.plot(dates, pm10, color = 'g')

plt.show()

我希望日期标记 x 轴,以及是否可以用更大的刻度标记每个新的一天。

【问题讨论】:

  • 您好,欢迎来到 SO。请提供数据样本(resultdates)。

标签: python matplotlib mysql-python


【解决方案1】:

如果没有您的数据示例,我无法重现您的问题,但我使用我的代码编写了一些代码。我的数据库是 sqlite3,但这并不重要。

获取数据

Pandas 有一个 read_sql_query 方法,您可能会发现它很有用。我正在使用它的parse_datesindex_col 将数据直接读入带有日期时间索引的pandas 数据框中。

# read_sql_query
with sqlite3.connect(my_db) as con:
    query = "SELECT humidity, ground_temp, ambient_temp, reading_timestamp from Measurements WHERE Measurements.stations_id = 591441"
    to_plot = pd.read_sql_query(sql=query, con=con, parse_dates=['reading_timestamp'], index_col='reading_timestamp')  

如果你更喜欢fetchall(),我可以达到同样的效果:

# fetchall
with sqlite3.connect(my_db) as con:
    query = "SELECT humidity, ground_temp, ambient_temp, reading_timestamp from Measurements WHERE Measurements.stations_id = 591441"
    to_plot = con.execute(query).fetchall()
    to_plot = pd.DataFrame(to_plot, columns=['humidity', 'ground_temp', 'ambient_temp', 'reading_timestamp']).set_index('reading_timestamp')

这是我的数据:

                           humidity  ground_temp  ambient_temp
reading_timestamp                                             
2019-05-21 14:55:02+00:00     70.66        14.31         16.33
2019-05-22 10:25:02+00:00     42.08        14.56         15.37
2019-05-23 12:25:02+00:00     55.07        15.75         17.49
2019-05-24 03:25:02+00:00     65.10        16.88         21.25
2019-05-27 13:55:02+00:00     57.46        18.50         25.12

索引是日期时间:

to_plot.index

DatetimeIndex(['2019-05-21 14:55:02+00:00', '2019-05-22 10:25:02+00:00',
               '2019-05-23 12:25:02+00:00', '2019-05-24 03:25:02+00:00',
               '2019-05-27 13:55:02+00:00'],
              dtype='datetime64[ns, UTC]', name='reading_timestamp', freq=None)

现在我有了一系列的绘图选项。

1。绘制整个 DataFrame

最简单、最快捷,但可定制性较差。

fig, ax = plt.subplots()
plt.plot(to_plot)
for tick in ax.get_xticklabels():
    tick.set_rotation(45)

2。绘制单个系列

更多控制,自动分配标签,以便我可以轻松添加图例。

fig, ax = plt.subplots()
ax.plot(to_plot['ambient_temp'], 'orange')
ax.plot(to_plot['ground_temp'], 'red')
ax.plot(to_plot['humidity'], 'blue')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()

3。绘图列表也应该可以工作

但我看不出这个用例有什么好处。 Plotting Series 给出相同的结果,但输入更少。

# Convert to lists
dates = list(to_plot.index)
ambient_temp = list(to_plot['ambient_temp'])
ground_temp = list(to_plot['ground_temp'])
humidity = list(to_plot['humidity'])
# Plot lists
fig, ax = plt.subplots()
ax.plot(dates, ambient_temp, 'orange', label='ambient_temp')
ax.plot(dates, ground_temp, 'red', label='ground_temp')
ax.plot(dates, humidity, 'blue', label='humidity')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()

大字体的天数

现在要让天以更大的字体显示,我建议您 set days as major ticks 使用 matplotlib.dates 然后 format them 按您想要的方式。

fig, ax = plt.subplots()
ax.plot(to_plot['ambient_temp'], 'orange')
ax.plot(to_plot['ground_temp'], 'red')
ax.plot(to_plot['humidity'], 'blue')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()

import matplotlib.dates as mdates
# mdates detects days
days = mdates.DayLocator()
# format for days
days_fmt = mdates.DateFormatter('%Y-%m-%d')
# days are major ticks
ax.xaxis.set_major_locator(days)
# format major ticks as days
ax.xaxis.set_major_formatter(days_fmt)
# give major ticks on x-axis a large font
ax.tick_params(axis='x', which='major', labelsize=13)

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多