使用seaborn.color_palette

问题描述 投票:0回答:1

现在,我的条形在蓝色光谱中颜色(由参数

coolwarm
给出)。例如,我如何更改这两种颜色和它们的顺序之间的分布,例如,将所有条的80%呈红色,而其余的(即20%)为蓝色? (现在是50-50%的比例)

使用Seaborn或Matplotlib Colormaps没有内置的方式,但这似乎是一种解决方案,可以解决窍门。

import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np ## function that generates a color palette def gen_palette(n_left, n_right, cmap_name="coolwarm", desat=0.999): """ n_left: number of colors from "left half" of the colormap n_right: number of colors from the "right half" cmap_name: name of the color map to use (ideally one of the diverging palettes) return: palette, list of RGB-triples """ palette_1 = sns.color_palette(palette=cmap_name, n_colors=2 * n_left, desat=desat)[:n_left] palette_2 = sns.color_palette(palette=cmap_name, n_colors=2 * n_right, desat=desat)[n_right:] return palette_1 + palette_2 ## generate example data N = 20 rng = np.random.default_rng(seed=42) y_vals = 10 * rng.random(N) df = pd.DataFrame( {"Col1": np.arange(N), "Col2": y_vals} ) ## build the color palette with the desired blue-red split n_red = round(0.8 * N) palette = gen_palette(N - n_red, n_red) ## plot plt.bar(df['Col1'], df['Col2'], width=0.97, color=palette)
python matplotlib seaborn matplotlibpyplot
1个回答
3
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.