Home > Back-end >  ConversionError: Failed to convert value(s) to axis units: '2015-01-01'
ConversionError: Failed to convert value(s) to axis units: '2015-01-01'

Time:02-12

I am trying to convert values to axis units. I checked codes with similar problems but none addressed this specific challenge. As can be seen in the image below, expected plot (A) was supposed to show month (Jan, Feb etc.) on the x-axis, but it was showing dates (2015-01 etc) in plot (B).

enter image description here

Below is the source code, kindly assist. Thanks.

plt.rcParams["font.size"] = 18

plt.figure(figsize=(20,5))
plt.plot(df.air_temperature,label="Air temperature at Frankfurt Int. Airport in 2015")
plt.xlim(("2015-01-01","2015-12-31"))
plt.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"])
plt.legend()
plt.ylabel("Temperature (°C)")
plt.show()

CodePudding user response:

A wise way to draw the plot with datetime is to use datetime format in place of str; so, first of all, you should do this conversion:

df = pd.read_csv(r'data/frankfurt_weather.csv')
df['time'] = pd.to_datetime(df['time'], format = '%Y-%m-%d %H:%M')

Then you can set up the plot as you please, preferably following enter image description here

  • Related