问题描述
我正在使用具有对数刻度的 seaborn 生成热图.如何将颜色条标签从科学记数法更改为普通数字.
I am generating a heatmap using seaborn which has a logarithmic scale. How can I change the colorbar labels from scientific notation to plain number.
import math
from matplotlib.colors import LogNorm
vmax=2
vmin=0.5
center = (vmax+vmin)/2
log_norm = LogNorm(vmin=vmin, vmax=vmin)
cbar_ticks = [0.5, 0.66, 1, 1.5, 2]
ax = sns.heatmap(corr, square=True, mask=mask, cmap=cmap_type, linewidths=.5, vmax=vmax, vmin=vmin, norm=log_norm, cbar_kws={"ticks": cbar_ticks}, center=center)
以下代码解决了科学记数法的问题:
The following code fixes the problem with scientific notation:
import matplotlib.ticker as tkr
formatter = tkr.ScalarFormatter(useMathText=True)
formatter.set_scientific(False)
cbar_kws={"ticks": cbar_ticks, "format": formatter}
但是 norm=log_norm
正在添加额外的刻度(请参见下图).如何删除这些?
but norm=log_norm
is adding additional ticks (Please see image below). How do I remove these?
推荐答案
以下代码有帮助.
对于问题的第一部分添加格式"在 cbar_kws 参数帮助.(https://stackoverflow.com/a/35419495/8881141):
For the first part of the problem adding "format" in cbar_kws parameters helped. (https://stackoverflow.com/a/35419495/8881141):
import matplotlib.ticker as tkr
formatter = tkr.ScalarFormatter(useMathText=True)
formatter.set_scientific(False)
ax = sns.heatmap(corr, square=True, mask=mask, cmap=cmap_type, linewidths=.5, vmax=vmax, vmin=vmin, norm=log_norm, cbar_kws={"ticks": cbar_ticks, "format": formatter}, center=center)
对于由 matplotlib 中的错误引起的第二部分,添加以下内容将删除次要刻度.(https://stackoverflow.com/a/65676007/11897903):
For the second part, which is caused due to a bug in matplotlib, adding the following removes the minor ticks. (https://stackoverflow.com/a/65676007/11897903):
ax.collections[0].colorbar.ax.yaxis.set_ticks([], minor=True)
这篇关于如何为具有对数刻度的seaborn热图以纯数字显示刻度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!