1

I'm plotting a correlation matrix using matplotlib but I have problems on the positioning of horizontal ticks.

Currently I'm creating a figure, placing the matrix plot and setting axes. The code is as follows:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rs = np.random.RandomState(0)
names = map(chr, range(65, 75))
df = pd.DataFrame(rs.rand(10, 10), columns=names)

correlations = df.corr()

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(correlations, vmin=-1, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0, 10, 1) #check
ax.set_xticks(ticks) #check
ax.set_yticks(ticks) #check
plt.show()

With the code, I get the following plot: Plot

Note that the first and last horizontal ticks are badly placed. It's like the first and last rows of the matrix are cut in half. Also note that if I removed the checked lines on the above code, the resulting axes are fixed, as on the following plot:

Plot

So something is wrong with the ticks settings. Any tip on how to solve this?

@Edit

Question have been marked as duplicate but I didn't find an answer to solve the problem involving matplotlib specifically. I ended up using seaborn's heatmap so I could apply the solution presented on the referenced post. You just need to set ylim according to your data dimension. The plot code is as follows:

fig = plt.figure()
ax = sns.heatmap(correlations, vmin=-1, vmax=1, cmap='viridis')
ax.set_ylim(10, 0)
ax.xaxis.tick_top()  # placing ticks on top
ax.xaxis.set_label_position('top')  # placing labels on top
ax.set_xticklabels(names)  # if you want labels
ax.set_yticklabels(names, rotation='horizontal')
plt.show()
  • Looks like a bug to me. I would check matplotlib's github to see if a related issue exists and -- if that is not the case -- raise the issue there. – Paul Brodersen Sep 11 '19 at 08:53

0 Answers0