如果没有您的数据示例,我无法重现您的问题,但我使用我的代码编写了一些代码。我的数据库是 sqlite3,但这并不重要。
获取数据
Pandas 有一个 read_sql_query 方法,您可能会发现它很有用。我正在使用它的parse_dates 和index_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)