简体   繁体   中英

How do I flip the color scaling of seaborn's sns.heatmap?

I have this piece of code that compares chess openings to their outcomes:

z = df2.groupby(["winner", "opening_name"]).size().unstack().fillna(0).astype(int)
fig, ax = plt.subplots(figsize=(32, 16))

sns.heatmap(z.apply(lambda x: x/x.sum()), xticklabels=True, yticklabels=True, cmap='YlOrBr',
        annot=True, linewidths=0.005, linecolor='black', annot_kws={"fontsize":16}, fmt='.2f', cbar=False)

plt.xticks(fontsize = 16)
plt.yticks(fontsize=16)
plt.show()
del z

This is the result: 在此处输入图片说明

Is there a way to change seaborn's sns.heatmap's configurations so that it applies the color scaling horizontally instead of vertically? Without changing the given values?

If I change the method's axis( z.apply(lambda x: x/x.sum(), axis = 1 ), it also changes the actual outcomes: 在此处输入图片说明

I want to apply the horizontal color scaling of the 2nd picture to the data of the first picture.

Instead of just setting annot=True , it can also be an array of values (or o labels). You can use a different data= parameter to define the coloring.

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

np.random.seed(31416)
weights = np.random.rand(20) ** 1.5
weights /= weights.sum()  # random weights summing to 1
N = 2000
df2 = pd.DataFrame({'winner': np.random.choice(['white', 'draw', 'black'], N, p=[0.47, 0.07, 0.46]),
                    'opening_name': np.random.choice([*'ABCDEFGHIJKLMNOPQRST'], N, p=weights)})

z = df2.groupby(["winner", "opening_name"]).size().unstack().fillna(0).astype(int)
fig, ax = plt.subplots(figsize=(32, 16))

sns.heatmap(data=z.apply(lambda x: x / x.sum(), axis=1),
            annot=z.apply(lambda x: x / x.sum()),
            xticklabels=True, yticklabels=True, cmap='YlOrBr',
            linewidths=0.005, linecolor='black', annot_kws={"fontsize": 16}, fmt='.2f', cbar=False, ax=ax)
ax.tick_params(labelsize=16)
plt.tight_layout()
plt.show()

更改注释的 sns.heatmap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM