LoginSignup
0
1

More than 1 year has passed since last update.

seabornヒートマップの数値表示の四捨五入対処

Last updated at Posted at 2022-08-18

概要

seabornでヒートマップを作る際に、セル内の数値表示が自動的に四捨五入されるらしい。
それによって、相関係数が1になるセルが大量に出てしまうことがあったので、対処した。

基本

以下のようなデータを用意する。

seaborn.py
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'A': range(10),
                   'B': [x**2 for x in range(10)],
                   'C': [x**3 for x in range(10)],
                   'D': [0, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
#    A   B    C   D
# 0  0   0    0   0
# 1  1   1    1   2
# 2  2   4    8   3
# 3  3   9   27   4
# 4  4  16   64   5
# 5  5  25  125   6
# 6  6  36  216   7
# 7  7  49  343   8
# 8  8  64  512   9
# 9  9  81  729  10

相関係数は以下のようになる。

seaborn.py
df_corr = df.corr()
print(df_corr)
#           A         B         C         D
# A  1.000000  0.962691  0.908434  0.996452
# B  0.962691  1.000000  0.985888  0.944573
# C  0.908434  0.985888  1.000000  0.886333
# D  0.996452  0.944573  0.886333  1.000000

結果は、

seaborn.py
fig, ax = plt.subplots(figsize=(50, 30))
sns.heatmap(df_corr, vmax=1, vmin=-1, center=0, cmap='RdBu', annot=True, annot_kws={"size": 15})

Figure_1.png
小数点第三位で四捨五入されている。

1. 表示桁数を増やす

セル内の数値表示の桁数を増やすために、オプションにfmt='.3f'を追加。(デフォルト値: ‘.2g’)

seaborn.py
sns.heatmap(df_corr, vmax=1, vmin=-1, center=0, cmap='RdBu', annot=True, annot_kws={"size": 15}, fmt='.3f')

結果は、
Figure_2.png
小数点第四位で四捨五入されている。

2. 任意の桁で切り捨て

小数点第三位以下を切り捨てたい場合、相関係数の数値を100倍して小数点以下を切り捨てた後、100で割る。

seaborn.py
df_corr = (df.corr() * 100).apply(np.floor) / 100
fig, ax = plt.subplots(figsize=(50, 30))
sns.heatmap(df_corr, vmax=1, vmin=-1, center=0, cmap='RdBu', annot=True, annot_kws={"size": 15}, fmt='.2f')

結果は、
Figure_3.png
小数点第三位以下が切り捨てられている。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1