我有這個代碼:
import numpy as np, matplotlib.pyplot as plt, seaborn as sns
fig = plt.figure(1)
sns.set(style="whitegrid", color_codes=True)
data=departments.value_counts()[:10]
pal = sns.color_palette("Blues_d", len(data))
rank = data.argsort().argsort()
sns.barplot(y=data.index, x=data, palette=np.array(pal[::1])[rank])
plt.title("Top departments", y=1.02)
fig.savefig('Top_departments', bbox_inches='tight', dpi=300)
我的資料如下所示:
Chemistry 19
Computer Science 13
Physics 10
Epidemiology and Biostatistics 8
Psychology 8
Mechanical and Industrial Engineering 8
Sociology 7
Academic 7
Bioengineering 7
Biochemistry and Molecular Genetics 6
附上劇情。問題是我得到了不同藍色陰影的條形圖:社會學、學術和生物工程,而它們應該是相同的陰影,因為它們具有相同的數值。

uj5u.com熱心網友回復:
問題的代碼似乎將順序顏色串列分配給從最大到最小的值。當遇到公平時,順序不是明確定義的,但該方法將始終分配不同的顏色,盡管值相等。該方法似乎旨在將條形從高到低著色,當它們尚未排序并且所有值都不同時。
這是一種按值著色的方法:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
fig = plt.figure(1)
sns.set(style="whitegrid", color_codes=True)
data = pd.Series([19, 13, 10, 8, 8, 8, 7, 7, 7, 6],
index=['Chemistry', 'Computer Science', 'Physics', 'Epidemiology and Biostatistics',
'Psychology', 'Mechanical and Industrial Engineering', 'Sociology',
'Academic', 'Bioengineering', 'Biochemistry and Molecular Genetics'])
cmap = sns.color_palette("Blues_d", as_cmap=True)
norm = plt.Normalize(data.min(), data.max())
sns.barplot(y=data.index, x=data, palette=cmap(norm(data.values)))
plt.title("Top departments", y=1.02)
plt.tight_layout()
plt.show()

要將條形從暗到亮著色,您可以直接使用反向調色板,而無需涉及argsort:
pal = sns.color_palette("Blues_r_d", len(data))
sns.barplot(y=data.index, x=data, palette=pal)
plt.title("Top departments", y=1.02)

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362628.html
標籤:matplotlib 海生
