如何在seaborn热图标签中使用科学记数法?

时间:2017-12-09 16:14:14

标签: python matplotlib format heatmap seaborn

我试图在python中使用seaborn获取热图。不幸的是,即使数字非常大,也没有使用科学记数法。我想知道是否有任何简单的方法可以转换为科学记数法或任何其他合理的格式。这是一段显示问题的代码:

import seaborn as sns 
import numpy as np
C_vals = np.logspace(3, 10, 8)
g_vals = np.logspace(-6, 2, 9)
score = np.random.rand(len(g_vals), len(C_vals))
sns.heatmap(score, xticklabels=C_vals, yticklabels=g_vals)

结果图如下

heatmap with bad format

2 个答案:

答案 0 :(得分:2)

如果您不能坚持sns.heatmap,那么使用pcolormesh

执行此操作可能更为自然
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

C_vals = np.logspace(3, 10, 8)
g_vals = np.logspace(-6, 2, 9)
score = np.random.rand(len(g_vals),len(C_vals))

fig, ax = plt.subplots()

ax.pcolormesh(C_vals, g_vals, score)
ax.set_yscale('log')
ax.set_xscale('log')
plt.show()

enter image description here

如下所述,pcolormesh并不以同样的方式居中。此外,它实际上下降了一个级别。虽然我有一个PR来改变这种行为,但这是一种解决方法。我承认在这一点上,它没有比使用heatmap输出搞乱更优雅。

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

C_vals = np.logspace(3, 10, 8)
g_vals = np.logspace(-6, 2, 9)
# make bracketing:
def midpointext(x):
    return np.hstack(( 1.5 * x[0] - 0.5 * x[1],
            x[:-1] + 0.5 * np.diff(x),
            1.5 * x[-1] - 0.5 * x[-2]))
newC = np.log10(C_vals)
newC = midpointext(newC)
newC = 10**newC
newg = np.log10(g_vals)
newg = midpointext(newg)
newg = 10**newg
score = np.random.rand(len(g_vals),len(C_vals))
fig, ax = plt.subplots()

ax.pcolormesh(newC, newg, score)
ax.set_yscale('log')
ax.set_xscale('log')
plt.show()

enter image description here

答案 1 :(得分:1)

热图允许从输入到xticklabels / yticklabels命令创建其标签。然后将它们放在轴上,因此没有数字格式来改变它们的外观。

选项是在将标签提供给热图之前格式化标签。为此,可以(错误地)使用matplotlib ScalarFormatter,这允许从浮点数自动生成MathText字符串。以下是一个例子:

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

C_vals = np.logspace(3, 10, 8)
g_vals = np.logspace(-6, 2, 9)
score = np.random.rand(len(g_vals),len(C_vals))

tick = ticker.ScalarFormatter(useOffset=False, useMathText=True)
tick.set_powerlimits((0,0))

tc = [u"${}$".format(tick.format_data(x)) for x in C_vals]
tg = [u"${}$".format(tick.format_data(x)) for x in g_vals]

sns.heatmap(score, xticklabels=tc, yticklabels=tg)

plt.show()

enter image description here

相关问题