我的盒子图的调色板有问题。我希望根据中值来分配颜色。中值越高,颜色越深。我选择了调色板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()
答案 0 :(得分: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()