ConversionError: Failed to convert value(s) to axis units: '2015-01-01'

Viewed 3834

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()

1 Answers

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 Object Oriented Interface:

plt.rcParams['font.size'] = 18
fig, ax = plt.subplots(figsize = (20,5))

ax.plot(df['time'], df['air_temperature'], label = 'Air temperature at Frankfurt Int. Airport in 2015')

ax.legend()
ax.set_ylabel('Temperature (°C)')

plt.show()

Then you can customize:

  • x ticks' labels format and position with matplotlib.dates:

    ax.xaxis.set_major_locator(md.MonthLocator(interval = 1))
    ax.xaxis.set_major_formatter(md.DateFormatter('%b'))
    
  • x axis limits:

    ax.set_xlim([pd.to_datetime('2015-01-01', format = '%Y-%m-%d'),
                 pd.to_datetime('2015-12-31', format = '%Y-%m-%d')])
    
  • capital first letter of x ticks' labels for months' names

    fig.canvas.draw()
    ax.set_xticklabels([month.get_text().title() for month in ax.get_xticklabels()])
    

Complete Code

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as md


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


plt.rcParams['font.size'] = 18
fig, ax = plt.subplots(figsize = (20,5))

ax.plot(df['time'], df['air_temperature'], label = 'Air temperature at Frankfurt Int. Airport in 2015')

ax.legend()
ax.set_ylabel('Temperature (°C)')

ax.xaxis.set_major_locator(md.MonthLocator(interval = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%b'))

ax.set_xlim([pd.to_datetime('2015-01-01', format = '%Y-%m-%d'),
             pd.to_datetime('2015-12-31', format = '%Y-%m-%d')])

fig.canvas.draw()
ax.set_xticklabels([month.get_text().title() for month in ax.get_xticklabels()])

plt.show()

enter image description here

Related