Home > Blockchain >  Error renaming x-axis labels from 24-hour format to 12-hour format
Error renaming x-axis labels from 24-hour format to 12-hour format

Time:10-05

I am trying to change my x-axis labels from 24-hour format to 12-hour, AM/PM format. However, when updating the x_ticks labels in matplotlib, I receive the following error:

ValueError: The number of FixedLocator locations (24), usually from a call to set_ticks, does not match the number of ticklabels (22).

I'm not sure why it is only counting 22 ticklabels when I indeed have 24 12-hour format labels to match the 24 24-hour format labels. My code below:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from datetime import timedelta, date   
    
inputs = data['datetime'].groupby(data['datetime'].dt.hour).count()

x_labels = ['12am','1am', '2am', '3am', '4am', '5am', '6am', '7am', '8am', '9am', '10am' '11am',
           '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', '9pm', '10pm' '11pm']

fig, ax = plt.subplots(1, 1)

ax.plot(inputs)

plt.title('UFO Sightings by Hour of Day', fontweight='bold', fontsize=15)
ax.set_xlabel('Hour of Day')
ax.set_ylabel('UFO Sightings Reported')

# add all x axis labels
ax.set_xticks(np.arange(len(inputs)), labels=x_labels)

plt.margins(0.001)
plt.tight_layout()
plt.show()

CodePudding user response:

You are missing commas in the x_labels. Right between 10 am and 11 am, and 10 pm and 11 pm.

  • Related