python - 设置 python 绘图的索引值

标签 python matplotlib

我正在一个图上绘制三条线。我希望 x 轴显示获取数据的日期以及从 00:00 到 24:00 的时间。现在,我的代码正确显示一天中的时间,但对于日期,显示的是当前日期(12-18),而不是显示数据记录的日期。我不确定如何纠正这个问题。另外,我的绘图仅显示 00:00 到 24:00 之间的时间而不显示 x 轴上的日期也是可以接受的。谢谢您的帮助!!

# set index as time for graphing
monAverages['Time'] = monAverages['Time'].apply(lambda x: pd.to_datetime(str(x)))
index = monAverages['Time']
index = index.apply(lambda x: pd.to_datetime(str(x)))
averagePlot = dfSingleDay
predictPlot = predictPlot[np.isfinite(predictPlot)]
datasetPlot = datasetPlot[np.isfinite(datasetPlot)]
predictPlot1 = pd.DataFrame(predictPlot)
datasetPlot1 = pd.DataFrame(datasetPlot)
averagePlot.set_index(index, drop=True,inplace=True)
datasetPlot1.set_index(index, drop=True,inplace=True)
predictPlot1.set_index(index, drop=True,inplace=True)
plt.rcParams["figure.figsize"] = (10,10)
plt.plot(datasetPlot1,'b', label='Real Data')
plt.plot(averagePlot, 'y', label='Average for this day of the week')
plt.plot(predictPlot1, 'g', label='Predictions')
plt.title('Power Consumption')
plt.xlabel('Date (00-00) and Time of Day(00)')
plt.ylabel('kW')
plt.legend()
plt.show()

enter image description here

最佳答案

您需要确保您只获得时间:

import matplotlib.dates as mdates
# set index as time for graphing
monAverages['Time'] = monAverages['Time'].apply(lambda x: pd.to_datetime(str(x)))
index = monAverages['Time']
#index = index.apply(lambda x: pd.to_datetime(str(x)))
dates= [dt.datetime.strptime(d,'%Y-%m-%d %H:%M:%S').time() for d in index]
averagePlot = dfSingleDay
predictPlot = predictPlot[np.isfinite(predictPlot)]
datasetPlot = datasetPlot[np.isfinite(datasetPlot)]
predictPlot1 = pd.DataFrame(predictPlot)
datasetPlot1 = pd.DataFrame(datasetPlot)

plt.rcParams["figure.figsize"] = (10,10)
plt.plot(dates,datasetPlot1,'b', label='Real Data')
plt.plot(dates,averagePlot, 'y', label='Average for this day of the week')
plt.plot(dates,predictPlot1, 'g', label='Predictions')
plt.title('Power Consumption')
plt.xlabel('Date (00-00) and Time of Day(00)')
plt.ylabel('kW')
plt.legend()
plt.show()

这里的代码解释了如何运行它

import datetime as dt
import matplotlib.pyplot as plt
dates = ['2019-12-18 00:00:00','2019-12-18 12:00:00','2019-12-18 13:00:00']
x = [dt.datetime.strptime(d,'%Y-%m-%d %H:%M:%S').time() for d in dates]
y = range(len(x))


plt.plot(x,y)
plt.gcf().autofmt_xdate()

plt.show()

关于python - 设置 python 绘图的索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59402506/

相关文章:

python - 如何传播通过 gdata python api 创建的谷歌日历事件的提醒?

python - 如何将 MySQL SOUNDEX 函数与 SQLAlchemy 结合使用

python - 如何将等高线图(matplotlib)转换为带标题的 FITS 格式?

python - '类型错误 : Not implemented for this type' when trying to make a Scatter plot in matplotlib

matplotlib - 如何在不扩展轴限制的情况下绘图?

python - 如何解决所有值都填None的问题?

python - 加快 Pandas 中日期计算之间的时间?

python - 类中属性的顺序

python - Matplotlib ArtistAnimation 给出 TypeError : 'AxesImage' object is not iterable

python - 如何在 matplotlib 中插入颜色以使其数量加倍