Reputation: 25
The following code generates a graph with few ticks but I need to display a tick every 4 or 6 hours. How can that we accomplished?
import matplotlib.dates as mdates
# Plot train and test so you can see where we have split
gdf = x_test[['AllAPIs']] \
.rename(columns={'AllAPIs': 'Test Set'}) \
.join(x_train.rename(columns={'AllAPIs': 'Training Set'}),
how='outer')
ax = gdf.plot(figsize=(12,5),title='API Calls')
plt.xticks(
rotation=45,
horizontalalignment='right',
fontweight='light',
fontsize='medium',
)
plt.show()
If I add the HourLocator as follows, I lose my ticks:
# set monthly locator
ax.xaxis.set_major_locator(mdates.HourLocator(interval=4))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H'))
What am I missing?????
Upvotes: 0
Views: 303
Reputation: 4021
Why don't you set the ticks
from the plt
object?
plt.xticks(
ticks = gdf.index.values
rotation=45,
horizontalalignment='right',
fontweight='light',
fontsize='medium',
)
This might set a lot of values, however, you can easily construct the xticks
parameter based on the index.
For example, asumming index values are sorted:
start = gdf.index.values[0]
end = gdf.index.values[-1]
ticks = pd.date_range(start, end, freq='4H')
labels = [x.strftime('%Y-%m-%d %H') for x in ticks]
plt.xtics(ticks=ticks, labels=labels)
Upvotes: 1