0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Seaborn.heatmapを使って特定の閾値で2色に塗り分けたヒートマップを作成

Last updated at Posted at 2025-09-29

要約

自分自身の備忘のため作成。

  • Excelの条件付き書式のように塗り分けたヒートマップをPythonで作成したかった
  • seabornのヒートマップのデフォルトでは、連続したカラーマップしか使えない
  • 引数のcmapcenterを使用することで解決
    • cmapにてlist形式で2色を指定し、centerで閾値を指定

背景

Excelでは以下のように条件付き書式から数クリックで一定の閾値以上を色分けしたヒートマップが作成できる。
image.png
同様のことをPythonで行う場合、第一選択はseabornを使用することだと思う。
ただ、seabornでは通常カラーマップは連続値しか指定できない。

解決策

stack overflowからの引用になってしまうが、以下のコードで解決。

heatmap.py
import pandas as pd
import seaborn as sns

df = pd.DataFrame({'a':[20, 13, 1, 11], 
                   'b':[15, 46, 32, 12],
                   'c':[67, 51, 33, 12],
                   'd':[6, 44, 86, 32]},
                   index=['', '', '', ''])
sns.heatmap(data=df,
            annot=True, 
            cmap=['white', 'red'],  # 2色を指定
            center=43.5  # 閾値を指定
            )
plt.show()     

download.png

参考資料

Creating a 2 colour heatmap with Python

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?