I am new to Matplotlib and I created a Heatmap of some number's correlation using the matshow function. Currently the code below only displays every 5th label (or tick), and I want it to display all of it. The code:
names = list('ABCDEDFGHIJKLMNOPQRSTU')
#just some random data for reproductability
df = pd.DataFrame(np.random.randint(0,100,size=(100, 22)), columns=names)
fig = plt.figure()
ax = fig.add_subplot(111)
cor_matrix = df.corr()
#these two lines don't change the outcome
ax.set_xticks(np.arange(len(names)))
ax.set_yticks(list(range(0,len(names))))
ax.matshow(cor_matrix)
plt.show()
The result looks like this:

I read this question: How to display all label values in matplotlib? But the answer there didn't work for me. The figure doesn't change if I don't set the ticks explicitly, or set them either way.
Also tried this questions's solution: How to make matplotlib show all x coordinates?
Which was plt.xticks(list(range(0,len(names)))), but that didn't do anything either.
You can use MultipleLocator:
from matplotlib.ticker import MultipleLocator # <- HERE
names = list('ABCDEDFGHIJKLMNOPQRSTU')
#just some random data for reproductability
df = pd.DataFrame(np.random.randint(0,100,size=(100, 22)), columns=names)
fig = plt.figure()
ax = fig.add_subplot(111)
cor_matrix = df.corr()
ax.matshow(cor_matrix)
ax.yaxis.set_major_locator(MultipleLocator(1)) # <- HERE
ax.xaxis.set_major_locator(MultipleLocator(1)) # <- HERE
plt.show()

The order of the matplotlib functions is causing the issue. By calling ax.matshow(cor_matrix) after the assignment of the x- and y-ticks they are overwritten again. By changing the ordering, everything should just work fine.
New order:
names = list('ABCDEDFGHIJKLMNOPQRSTU')
#just some random data for reproductability
df = pd.DataFrame(np.random.randint(0,100,size=(100, 22)), columns=names)
fig = plt.figure()
ax = fig.add_subplot(111)
cor_matrix = df.corr()
ax.matshow(cor_matrix)
ax.set_xticks(np.arange(len(names), step=1))
ax.set_yticks(list(range(0,len(names))))
plt.show()
Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With