making colorbar with scientific notation in seabor

2019-07-04 22:04发布

问题:

I am plotting the following heatmap in seaborn. the dataframe is read from the foll. csv file: https://www.dropbox.com/s/mb3wc8mmis0m7g6/df_trans.csv?dl=0

ax = sns.heatmap(df, linewidths=.1, linecolor='gray', cmap=sns.cubehelix_palette(light=1, as_cmap=True))
locs, labels = plt.xticks()
plt.setp(labels, rotation=0)
locs, labels = plt.yticks()
plt.setp(labels, rotation=0)

How can I modify the colorbar numbers so that they 160000 shows up as 1.6 with a 10^5 on top of colorbar. I know hot to do this in matplotlib but not in seaborn:

import matplotlib.ticker as tkr
formatter = tkr.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
ax.yaxis.set_major_formatter(formatter)

回答1:

Pass your formatter object through the cbar_kws:

import numpy as np
import seaborn as sns
import matplotlib.ticker as tkr

formatter = tkr.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-2, 2))

x = np.exp(np.random.uniform(size=(10, 10)) * 10)
sns.heatmap(x, cbar_kws={"format": formatter})



回答2:

With seaborn, you can pass the formatter to the colorbar when you create the heatmap through the cbar_kws argument.

Using the seaborn documentation as an example...

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()

import matplotlib.ticker as tkr
formatter = tkr.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)

uniform_data = np.random.rand(10, 12) * 100000000

ax = sns.heatmap(uniform_data,
                 cbar_kws={'format':formatter}
                )