2017-07-07 105 views
0

我的盒子情節調色板有問題。我希望顏色根據中位值分配。中值越高,顏色越深。我選擇了調色板YlGnBu。然而,顏色分配就像一個梯度 - 較深的顏色在右邊,而淺色在左邊:如何根據箱形圖中的中值分配顏色?

df = sns.load_dataset("tips") 

norm = plt.Normalize(df["total_bill"].values.min(), df["total_bill"].values.max()) 
colors = plt.cm.YlGnBu(norm(df["total_bill"])) 
flierprops = dict(markerfacecolor='0.75', markersize=5,linestyle='none') 

plt.figure(figsize=(12,8)) 
ax = sns.boxplot(x="day", y="total_bill", data=df, 
       palette=colors, 
       flierprops=flierprops) # hue="smoker", 
plt.xticks(rotation='vertical') 
ax.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x,p: str(x)+":00")) 
ax.get_yaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x,p: locale.format('%d', x, 1))) 
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0) 
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5) 
plt.show() 

回答

1

您的問題是你設置你的顏色表基礎上在全量程total_bill值你的數據幀。如果您希望色彩映射反映一週中每天的中值,則必須使用這些中值設置。

df = sns.load_dataset("tips") 

median_vals = df.groupby('day')['total_bill'].median() 
norm = plt.Normalize(median_vals.min(), median_vals.max()) 
colors = plt.cm.YlGnBu(norm(median_vals)) 

plt.figure(figsize=(12,8)) 
ax = sns.boxplot(x="day", y="total_bill", data=df, palette=colors) 
plt.show() 

enter image description here