Seaborn heatmap is generating additional ticks on colorbar when using log scale

你离开我真会死。 提交于 2021-01-29 11:26:39

问题


I am trying to make a heatmap with logarithmic colorbar. But it keeps generating its own ticks and ticklabels along with the ones I input.

I originally posted this to reformat the tick labels from scientific notation to plain but then ran into this problem.

import numpy as np
import seaborn as sns
from matplotlib.colors import LogNorm
import matplotlib.ticker as tkr

matrix = np.random.rand(10, 10)/0.4
vmax=2
vmin=0.5

cbar_ticks = [0.5, 0.75, 1, 1.33, 2]
formatter = tkr.ScalarFormatter(useMathText=True)
formatter.set_scientific(False)

log_norm = LogNorm(vmin=vmin, vmax=vmax)
ax = sns.heatmap(matrix, square=True, vmax=vmax, vmin=vmin, norm=log_norm, cbar_kws={"ticks": cbar_ticks, "format": formatter})


回答1:


With a logarithmic axis, often also minor ticks are set (they help to know where different values are situated and they enforce the logarithmic look). In this case, the default ticks only include one tick (at 1.0) which isn't enough to see which value correspond to which color.

With cbar_kws only the major ticks can be changed. You can suppress the minor ticks explicitly:

import numpy as np
import seaborn as sns
from matplotlib.colors import LogNorm
import matplotlib.ticker as tkr
from matplotlib import pyplot as plt

matrix = np.random.rand(10, 10) / 0.4
vmax = 2
vmin = 0.5

cbar_ticks = [0.5, 0.75, 1, 1.33, 2]
formatter = tkr.ScalarFormatter(useMathText=True)
formatter.set_scientific(False)

log_norm = LogNorm(vmin=vmin, vmax=vmax)
ax = sns.heatmap(matrix, square=True, vmax=vmax, vmin=vmin, norm=log_norm,
                 cbar_kws={"ticks": cbar_ticks, "format": formatter})
ax.collections[0].colorbar.ax.yaxis.set_ticks([], minor=True)
plt.show()



来源:https://stackoverflow.com/questions/65675891/seaborn-heatmap-is-generating-additional-ticks-on-colorbar-when-using-log-scale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!