Separately adjust vertical and horizontal linewidth for seaborn.heatmap

Question:

The parameter linewidth adjusts the size of the space between each cell. For example:

import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np; np.random.seed(0)
uniform_data = np.random.rand(2000, 6)
ax = sns.heatmap(uniform_data)

normal heatmap

plt.clf()
ax = sns.heatmap(uniform_data, linewidth=0.0001)

enter image description here

You can only see white, because my heatmap shape is significantly skewed: 2000 rows and 6 columns. I would like to have a vertical white space between each cell column. Therefore, I need to find a way to adjust the vertical linewidth separately. How can that be achieved?

Asked By: cmosig

||

Answers:

Setting the linewidth applies to the edgewidth of a rectangle around each cell. To only have vertical lines, axvline() draws a vertical line, default from the top to the bottom of the plot. To just separate the columns, lines can be drawn at positions 1,2,…n-1. Also having a line at positions 0 and n helps to make the columns visually equally wide.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

uniform_data = np.random.rand(200, 6)
ax = sns.heatmap(uniform_data)
for i in range(uniform_data.shape[1]+1):
    ax.axvline(i, color='white', lw=2)
plt.tight_layout()
plt.show()

resulting plot

Answered By: JohanC
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.