使用“matplotlib”和“pandas”表示连续图形`

2024-04-20 06:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据帧是这样的-

   Energy_MWh    Month
0   39686.82    1979-01
1   35388.78    1979-02
2   50134.02    1979-03
3   37499.22    1979-04
4   20104.08    1979-05
5   17440.26    1979-06

一直持续到2015-12月。所以你可以想象所有的数据。你知道吗

我想用months作为x轴,用Energy_MWh作为y轴绘制一个连续图。如何用matplotlib最好地表示这一点?你知道吗

我还想知道是否有一种方法可以将1979-01作为Jan-1979打印在x轴上,以此类推。可能是lambda函数之类的。你知道吗


Tags: 数据方法lambda函数matplotlib绘制janenergy
2条回答

this answer大量借用,你应该出去投票:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

df = <set_your_data_frame_here>

myDates = pd.to_datetime(df['Month'])
myValues = df['Energy_MWh']
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%b-%Y")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

enter image description here

Month设置为索引:

df.set_index('Month', inplace=True)

将索引转换为Datetime

df.index = pd.DatetimeIndex(df.index)

绘图:

df.plot()

相关问题 更多 >