Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib matshow: show all tick labels

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.

like image 452
harcipulyka Avatar asked May 06 '26 16:05

harcipulyka


2 Answers

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

like image 153
Corralien Avatar answered May 08 '26 06:05

Corralien


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

like image 29
Marcello Zago Avatar answered May 08 '26 07:05

Marcello Zago



Donate For Us

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