2
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.set_label_position('top') # <-- This doesn't work!

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

Above code is from: Moving x-axis to the top of a plot in matplotlib

How can I change output from this script so that it looks aesthetically more like this picture:
enter image description here

Any solution using python matplotlib or seaborn works. I want to insert white between the cells, have the cells be square and also control their size

Community
  • 1
  • 1
user308827
  • 21,227
  • 87
  • 254
  • 417

1 Answers1

3

I think you need 2 tricks. First, add the line

ax.set_aspect('equal')

to make the cells appear as squares (assuming that you have an equal number on the x- and y-axes, as in your example). If you have x squares on the x-axis and y squares on the y-axis, I suspect that you could instead do,

ax.set_aspect(float(y) / float(x))

Second, you need to add edgecolor to the cells and make the edges thick, so modify your line to e.g.,

heatmap = ax.pcolor(data, cmap=plt.cm.Blues, edgecolor='white', linewidths=10)

The result is

enter image description here

innisfree
  • 2,044
  • 1
  • 14
  • 24