【问题标题】:Seaborn:如何为每个 seaborn violinplot 应用自定义颜色?
【发布时间】:2022-01-23 07:38:14
【问题描述】:

如何使用自定义颜色来获得这样的分割小提琴图:image source

标准示例仅使用 hue 参数显示 2 种颜色。

【问题讨论】:

    标签: python matplotlib colors seaborn violin-plot


    【解决方案1】:

    Seaborn 仅支持分体式小提琴的 2 个色调值。您需要遍历创建的小提琴并更改它们的颜色。

    这是一个例子:

    from matplotlib import pyplot as plt
    from matplotlib.colors import to_rgb
    from matplotlib.collections import PolyCollection
    import seaborn as sns
    import pandas as pd
    
    tips = sns.load_dataset('tips')
    ax = sns.violinplot(x="day", y="total_bill", hue="smoker", palette=['.4', '.7'], data=tips, split=True, inner='box')
    colors = sns.color_palette('Set2')
    for ind, violin in enumerate(ax.findobj(PolyCollection)):
        rgb = to_rgb(colors[ind // 2])
        if ind % 2 != 0:
            rgb = 0.5 + 0.5 * np.array(rgb)  # make whiter
        violin.set_facecolor(rgb)
    plt.show()
    

    以下方法添加自定义图例:

    from matplotlib import pyplot as plt
    from matplotlib.colors import to_rgb
    from matplotlib.collections import PolyCollection
    from matplotlib.legend_handler import HandlerTuple
    import seaborn as sns
    import numpy as np
    
    tips = sns.load_dataset('tips')
    ax = sns.violinplot(x="day", y="total_bill", hue="smoker", palette=['.2', '.5'], data=tips, split=True, inner='box')
    colors = ['dodgerblue', 'crimson', 'gold', 'limegreen']
    handles = []
    for ind, violin in enumerate(ax.findobj(PolyCollection)):
        rgb = to_rgb(colors[ind // 2])
        if ind % 2 != 0:
            rgb = 0.5 + 0.5 * np.array(rgb)  # make whiter
        violin.set_facecolor(rgb)
        handles.append(plt.Rectangle((0, 0), 0, 0, facecolor=rgb, edgecolor='black'))
    ax.legend(handles=[tuple(handles[::2]), tuple(handles[1::2])], labels=tips["smoker"].cat.categories.to_list(),
              title="Smoker", handlelength=4, handler_map={tuple: HandlerTuple(ndivide=None, pad=0)})
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 2020-10-21
      • 2020-10-17
      • 1970-01-01
      • 2020-04-10
      • 2018-12-15
      • 2021-07-06
      • 2020-06-21
      • 2021-10-29
      相关资源
      最近更新 更多