python - Plotting time series by year only in Matplotlib
问题描述
I have a series that have dates in datetime format that look like:
2015-05-10 00:00:00
I would like to plot two different values in my dataframe over the same time periods and I've tried:
plt.subplot(211)
plt.plot(df['Date'].dt.year, df['Avg'], color='r')
plt.show()
plt.subplot(212)
plt.plot(df['Date'].dt.year, df['MW'], color='b')
plt.show()
But this gives me a strange format that can't even be dealt with by changing the ['Date'] column outside of plotting.
It plots as:
2015.0 2015.5 2016.0 2016.5.....etc
Tried changing to float form as well but to no avail.
All I want is one yearly tick over the entire series from 2015 to 2018 but when I convert to a string or integer I get something that looks like:
解决方案
.set_xticks
在我看来,这是设置您在 x 轴上看到的值的最易读的方法。
import pandas as pd
import matplotlib.pyplot as plt
data =[ {"Date":"2015-05-10", "Avg":34}, {"Date":"2016-05-10", "Avg":32},
{"Date":"2017-05-10", "Avg":31}, {"Date":"2015-05-10", "Avg":31},
{"Date":"2015-05-10", "Avg":26}, {"Date":"2015-05-10", "Avg":29}]
df = pd.DataFrame(data)
ax = plt.subplot(111)
ax.plot(df['Date'].dt.year, df['Avg'], color='r')
ax.set_xticks([2015, 2016, 2017])
plt.show()
看起来您也遇到了问题,因为您每年都有多个值,因此它绘制了您看到的垂直线。使用 pandas.groupby
函数的聚合值似乎是您想要的。
df["Year"] = df["Date"].dt.year
df = df.groupby("Year").mean().reset_index()
ax = plt.subplot(211)
ax.plot(df.Year, df['Avg'], color='r')
ax.set_xticks([2015, 2016, 2017])
plt.show()
推荐阅读
- r - 使用 ggplot 函数根据累积数据创建绘图
- rest - 如何在 Delphi 中对包含已经 URLEncoded 部分的字符串进行 URLEncode?
- kotlin - 我有一个 lateinit 错误“kotlin.UninitializedPropertyAccessException:lateinit 属性对话框尚未初始化”
- python - 有没有办法接受用户输入并将其与值 PYTHON SQL 匹配
- swift - 动画调整大小的单元格下方的单元格以一种奇怪的方式跳跃
- algorithm - 给定运行时数据,如何知道排序程序是使用冒泡排序还是插入排序?
- python - 根据列值在数据框中插入新行
- html - 如何将选择选项重新定位到屏幕中间
- android - Android Studio 数据绑定问题
- python - 将行附加到空数据帧返回空数据帧