Я не смог воспроизвести вашу проблему без примера ваших данных, но я написал некоторый код, используя мой. Моя база данных - sqlite3, но это не имеет значения.
Получение данных
У панд есть метод read_sql_query
, который может оказаться полезным. Я использую его parse_dates
и index_col
для чтения данных прямо в кадр данных pandas с индексом datetime.
# 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)
![plot_df](https://i.stack.imgur.com/OGrOo.png)
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()
![plot_series](https://i.stack.imgur.com/KeDYu.png)
3. Списки печати должны также работать
Но я не вижу никакой пользы в этом случае использования. Серия Plotting дает тот же результат с меньшим набором текста.
# 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()
Дней крупным шрифтом
Теперь, чтобы дни отображались более крупным шрифтом, я бы посоветовал вам установить дни в качестве основных отметок , используя matplotlib.dates
, а затем отформатировать их так, как вы хотите.
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)
![plt_bigdays](https://i.stack.imgur.com/mXlu2.png)