本文介绍了使用对数刻度时,Seaborn 热图会在颜色条上生成额外的刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用对数颜色条制作热图.但它会不断生成自己的刻度和刻度标签以及我输入的刻度.

我最初发布

解决方案

对于对数轴,通常还会设置小刻度(它们有助于了解不同值的位置并强制对数外观).在这种情况下,默认刻度仅包括一个刻度(在 1.0 处),这不足以查看哪个值对应于哪种颜色.

使用 cbar_kws 只能更改主要刻度.您可以显式抑制次要刻度:

将 numpy 导入为 np将 seaborn 作为 sns 导入从 matplotlib.colors 导入 LogNorm导入 matplotlib.ticker 作为 tkr从 matplotlib 导入 pyplot 作为 plt矩阵 = np.random.rand(10, 10)/0.4vmax = 2最小 = 0.5cbar_ticks = [0.5, 0.75, 1, 1.33, 2]格式化程序 = tkr.ScalarFormatter(useMathText=True)formatter.set_scientific(假)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()

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})
解决方案

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()

这篇关于使用对数刻度时,Seaborn 热图会在颜色条上生成额外的刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 20:05