簡體   English   中英

Seaborn 熱圖中按行進行顏色縮放

[英]Color scale by rows in Seaborn Heatmap

我想在 Seaborn 中制作熱圖,其中顏色按行縮放。 我的意思是,一行中的最高值在圖例中具有最高的顏色,而在一行中的最低值 - 最低。 我怎么能做到?

這是我的代碼:

sales = sales.pivot_table(index='Sources', columns='Category', values='Value')

sns.heatmap(sales,annot=True, cmap='coolwarm',fmt='g',linewidths=1,linecolor='black',).set_title('Sales')

這是我從中得到的熱圖

在此處輸入圖片說明

使用numpy.argsort您可以找到每行中值的順序。 使用結果作為着色的基礎將為您提供每行的映射。

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedFormatter

data = np.random.randint(1,250, size=(10,6))
b = np.argsort(np.argsort(data, axis=1), axis=1)

im = plt.imshow(b, aspect="auto", cmap="coolwarm")
plt.colorbar(im, ticks=np.array([0.0, 0.5, 1.0])*b.max(), 
             format=FixedFormatter(["low", "middle", "high"]))

for i in range(data.shape[0]):
    for j in range(data.shape[1]):
        plt.text(j,i,data[i,j], ha="center", va="center")

plt.show()

在此處輸入圖片說明

使用 pandas 將每行除以其最大值,我們得到一個着色,其中最大值為深紅色,其他列取決於它們與最大值的關系。 因此,幾乎等於最大值的列將是較輕的 ted。 只有一半銷售額的列將顯示為白色。 幾乎沒有銷售額的列將是藍色的。

顏色條表示與每行最大值相比的百分比。

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import random

sources = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
categories = [f'Cat {i}' for i in range(1, 5)]
data = [[s, c, random.randint(2, 50)] for s in sources for c in categories]
sales = pd.DataFrame(data, columns=['Sources', 'Category', 'Value'])

# create a dataframe grouped by Sources and Category
per_source_cat = sales.groupby(['Sources', 'Category']).agg({'Value': 'sum'})
# calculate the maximum for each source
max_per_source = sales.groupby(['Sources']).agg({'Value': 'max'})
# divide the sales of each source by the maximum for that source
per_source_cat = per_source_cat.div(max_per_source, level='Sources') * 100
# convert to a pivot table
per_source_cat = per_source_cat.pivot_table(index='Sources', columns='Category', values='Value')
# convert the sales to a compatible pivot table
sales = sales.pivot_table(index='Sources', columns='Category', values='Value')
sns.heatmap(per_source_cat, cmap='coolwarm', annot=sales, fmt='g', linewidths=1, linecolor='black', ).set_title('Sales')
plt.show()

示例熱圖

或者,假設您想為最高的紅色和最低的藍色着色,而不管它們是否靠近。 然后,減去最小值並除以最大值和最小值之間的差值可以定義着色。 完全相等的行會導致除以零,這可以使用fillna進行處理。

# create a dataframe grouped by Sources and Category
per_source_cat = sales.groupby(['Sources', 'Category']).agg({'Value': 'sum'})
# calculate the maximum and minimum for each source
max_per_source = sales.groupby(['Sources']).agg({'Value': 'max'})
min_per_source = sales.groupby(['Sources']).agg({'Value': 'min'})
# subtract the minimum and divide by the difference between maximum and minimum
per_source_cat = (per_source_cat - min_per_source) / (max_per_source - min_per_source) * 100
# in the case of all equal, there will be a division by 0, set every value to 100 %
per_source_cat = per_source_cat.fillna(100.0)

繪制最低顏色的藍色

現在,顏色條指示最高為 100%,最低為 0%,其他按比例着色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM