转换错误:无法将值转换为轴单位:“2015-01-01”

Dee*_*one 4 python datetime matplotlib dataframe pandas

我正在尝试将值转换为轴单位。我检查了具有类似问题的代码,但没有一个解决了这个特定的挑战。如下图所示,预期图 (A) 应该在 x 轴上显示月份(一月、二月等),但图 (B) 中却显示日期(2015 年 1 月等)。

\n

在此输入图像描述

\n

下面是源码,请帮忙。谢谢。

\n
plt.rcParams["font.size"] = 18\n\nplt.figure(figsize=(20,5))\nplt.plot(df.air_temperature,label="Air temperature at Frankfurt Int. Airport in 2015")\nplt.xlim(("2015-01-01","2015-12-31"))\nplt.xticks(["2015-{:02d}-15".format(x) for x in range(1,13,1)],["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"])\nplt.legend()\nplt.ylabel("Temperature (\xc2\xb0C)")\nplt.show()\n\n
Run Code Online (Sandbox Code Playgroud)\n

Zep*_*hyr 5

使用日期时间绘制绘图的明智方法是使用datetimeformat 代替str; 因此,首先,您应该进行此转换:

\n
df = pd.read_csv(r\'data/frankfurt_weather.csv\')\ndf[\'time\'] = pd.to_datetime(df[\'time\'], format = \'%Y-%m-%d %H:%M\')\n
Run Code Online (Sandbox Code Playgroud)\n

然后您可以根据需要设置绘图,最好遵循面向对象的界面

\n
plt.rcParams[\'font.size\'] = 18\nfig, ax = plt.subplots(figsize = (20,5))\n\nax.plot(df[\'time\'], df[\'air_temperature\'], label = \'Air temperature at Frankfurt Int. Airport in 2015\')\n\nax.legend()\nax.set_ylabel(\'Temperature (\xc2\xb0C)\')\n\nplt.show()\n
Run Code Online (Sandbox Code Playgroud)\n

然后您可以自定义:

\n\n

完整代码

\n
import pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as md\n\n\ndf = pd.read_csv(r\'data/frankfurt_weather.csv\')\ndf[\'time\'] = pd.to_datetime(df[\'time\'], format = \'%Y-%m-%d %H:%M\')\n\n\nplt.rcParams[\'font.size\'] = 18\nfig, ax = plt.subplots(figsize = (20,5))\n\nax.plot(df[\'time\'], df[\'air_temperature\'], label = \'Air temperature at Frankfurt Int. Airport in 2015\')\n\nax.legend()\nax.set_ylabel(\'Temperature (\xc2\xb0C)\')\n\nax.xaxis.set_major_locator(md.MonthLocator(interval = 1))\nax.xaxis.set_major_formatter(md.DateFormatter(\'%b\'))\n\nax.set_xlim([pd.to_datetime(\'2015-01-01\', format = \'%Y-%m-%d\'),\n             pd.to_datetime(\'2015-12-31\', format = \'%Y-%m-%d\')])\n\nfig.canvas.draw()\nax.set_xticklabels([month.get_text().title() for month in ax.get_xticklabels()])\n\nplt.show()\n
Run Code Online (Sandbox Code Playgroud)\n

在此输入图像描述

\n