Reputation: 1040
I have created a basic heat map in python using the below:
import pandas as pd
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
# FILE INPUT PATH
FILE_PATH_INPUT = 'C:/Python/'
# IMPORT FILE
flights_raw = pd.read_excel(FILE_PATH_INPUT+'flights.xlsx', sheetname='flights')
flights_raw["month"] = pd.Categorical(flights_raw["month"], flights_raw.month.unique())
flights_raw.head()
# CREATE MATRIX
flight_matrix = flights_raw.pivot("month", "year", "passengers")
flight_matrix
fig = plt.figure()
fig, ax = plt.subplots(1,1, figsize=(12,12))
heatplot = ax.imshow(flight_matrix, cmap='binary')
ax.set_xticklabels(flight_matrix.columns, rotation = 90)
ax.set_yticklabels(flight_matrix.index)
tick_spacing = 1
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
ax.yaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
ax.set_title("Variance of Delivery Days By Period")
ax.set_xlabel('DAYS LATE (-EARLY)')
ax.set_ylabel('PERIOD')
Which results in the below plot.
However my axis labels seem to be in the wrong place.
My Y Axis should all be dropped down a space, and my horizontal axis should all be shifted to the right, the data should span from 1 - 14, not 2-14.
I have tried changing the tick spacing but this just stretches out the positioning, I am thinking i may need to offset the positioning of the labels ?
Any advice is welcome.
Upvotes: 1
Views: 90
Reputation: 339120
You should never set the ticklabels without setting the ticks as well. What this essentially does is keeping an AutoLocator
for the axes but using a FixedFormatter
for the labels.
So when using a FixedFormatter
as is done with set_xticklabels
always make sure to also use a FixedLocator
, e.g. using set_xticks
.
ax.set_xticks(list(range(len(labels))))
ax.set_xticklabels(labels)
Of course after setting the formatter and locator this way, you should not set them to something different later. So the following two lines need to be deleted from the code.
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
ax.yaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
Upvotes: 2