Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

python - Seaborn Heatmap with logarithmic-scale colorbar

Is there a way to set the color bar scale to log on a seaborn heat map graph?
I am using a pivot table output from pandas as an input to the call

 sns.heatmap(df_pivot_mirror,annot=False,xticklabels=256,yticklabels=128,cmap=plt.cm.YlOrRd_r)

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have a current install of seaborn, norm=LogNorm() in the call to heatmap works now. (Pointed out in the comments -- thank you.) Adding this to one of the seaborn examples:

import numpy as np
import seaborn as sns; sns.set_theme(style='white')
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm, Normalize
from matplotlib.ticker import MaxNLocator

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")


f3, ax5 = plt.subplots(1,1)
sns.heatmap(flights, square=True, norm=LogNorm())

Heatmap with lognorm colorbar, four tick labels

You can pass through colorbar arguments as keywords in the seaborn wrapper, but they sometimes collide with the seaborn choices:

sns.heatmap(flights, square=True, norm=LogNorm(), cbar_kws={'ticks':MaxNLocator(2), 'format':'%.e'})

Heatmap with lognorm colorbar, four tick labels with inconsistent numerical formatting

For comparison, this is the matplotlib heatmap without seaborn's improvements -- the colorbar arguments have both been applied:

f5, ax6 = plt.subplots(1,1)
im6 = plt.imshow(flights, norm=LogNorm())
cbar6 = ax.figure.colorbar(im6, ax=ax6, ticks=MaxNLocator(2), format='%.e')

Heatmap with lognorm colorbar, two tick labels, scientific number formatting

If you have to use an older install and LogNorm doesn't work in seaborn, see the previous versions of this answer for a workaround.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...