2

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: enter image description here

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.

harcipulyka
  • 117
  • 1
  • 6

2 Answers2

5

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()

heatmap

Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Thanks, that solved it. I actually tried that as well, but I put it before the `ax.matshow(cor_matrix)` line, and that way it doesn't do anything. – harcipulyka Sep 23 '21 at 19:12
  • Yes because `matshow` modify the x and y axis. So you have to override its settings after the plot function. – Corralien Sep 23 '21 at 19:14
  • When I put `ax.matshow(data, cmap=plt.cm.Blues, alpha=0.7)` after ` ax.xaxis.set_major_locator` it did not work; just a note for others – Alex Punnen Oct 21 '22 at 06:21
  • 1
    @AlexPunnen. This doesn't work because `ax.matshow` resets the figure, so you need to customize the settings AFTER it's created. – Corralien Oct 21 '22 at 07:25
1

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:

enter image description here

Marcello Zago
  • 629
  • 5
  • 19