【发布时间】:2020-10-30 13:23:57
【问题描述】:
如标题所示,我正在尝试更改图表的日期时间格式。我做了一些研究,发现我的代码中包含了 2 行(#option 1 和 #option 2)。他们没有给出错误,但输出格式不是我指定的格式。请阅读下面的代码并查看加载的图像。我究竟做错了什么?任何帮助将不胜感激。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from datetime import datetime
# create an array of 5 dates starting at '2020-02-24', one every month
rng = pd.date_range('2020-02-24', periods=5, freq='MS')
df_1 = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))})
df_1.set_index("Date", inplace = True)
df_2 = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))})
df_2.set_index("Date", inplace = True)
print(df_1, "\n")
print(df_2)
#Set up figure
fig, ax = plt.subplots(1,2, figsize=(11,5))
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.3, hspace=None) #Adjust space between graphs
#Plot 1
df_1.plot(ax=ax[0], kind="line", color="forestgreen", stacked=False, rot=90)
ax[0].set_axisbelow(True) # To put plot grid below plots
ax[0].yaxis.grid(color='gray', linestyle='dashed')
ax[0].xaxis.grid(color='gray', linestyle='dashed')
# option 1
ax[0].set_xticklabels([pandas_datetime.strftime("%d %b %Y") for pandas_datetime in df_1.index])
# option 2
ax[0].xaxis.set_major_formatter(DateFormatter('%d %b %Y'))
ax[0].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) # Put legend on top
ax[0].set(xlabel=None, ylabel="Amount %") # Set axis label
#Plot 2
df_2.plot(ax=ax[1], kind='line', stacked=False, color="violet", rot=90)
ax[1].set_axisbelow(True) # To put plot grid below plots
ax[1].yaxis.grid(color='gray', linestyle='dashed')
ax[1].xaxis.grid(color='gray', linestyle='dashed')
# option 1
ax[1].set_xticklabels([pandas_datetime.strftime("%d %b %Y") for pandas_datetime in df_2.index])
# option 2
ax[1].xaxis.set_major_formatter(DateFormatter('%d %b %Y'))
ax[1].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) # Put legend on top
ax[1].set(xlabel=None, ylabel="Amount %") # Set axis label
#Save file as png
date_now = datetime.now().strftime('%d-%m-%Y')
fig.savefig("Test_{}.png".format(date_now), bbox_inches='tight')
【问题讨论】:
标签: pandas datetime matplotlib