【问题标题】:How to apply a linestyle to a specific line in Seaborn lineplot?如何将线条样式应用于 Seaborn 线图中的特定线条?
【发布时间】:2021-04-09 10:35:48
【问题描述】:

我有一个数据框,其中 Products 列中有许多不同的项目,我们只显示几个:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = np.array([[1, 1, 570], [2, 1, 650], [1, 2, 27], [2, 2, 64], [1, 3, 125], [2, 3, 216],  
                  [1, 'item_1', 343], [2, 'item_1', 340], [1, 'item_2', 343], [2, 'item_2', 345]])
df = pd.DataFrame(data=data, columns=["Flag", "Products", "Value"])

我正在使用 Seaborn 获得以下线图:

sns.set_theme()
sns.set_style("ticks")
sns.set_context("paper")

fig1, ax1 = plt.subplots()
sns.lineplot(data=df, x="Flag", y="Value", 
             hue="Products", style="Products", ax=ax1)
plt.legend(bbox_to_anchor=(1.02, 1),borderaxespad=0)
fig1.tight_layout()

通过这种方式,所有线条都有 Seaborn“选择”的样式,但我需要为名为“item_1”和“item_2”的产品设置特定颜色和线条样式(不是虚线)。 到目前为止,我已经找到了以下解决方案:

palette = {c:'red' if c=='item_1' else 'blue' for c in df.Products.unique()}
sns.lineplot(data=df, x="Flag", y="Value", 
             hue="Products", style="Products", palette=palette, ax=ax1)

所以,我可以只为 item_1 设置红色,但所有其他行都是蓝色的,而我想:

  • 为 items_1 和 items_2 设置红色和非虚线
  • 为所有其他线条设置另一个调色板(例如明亮)

有可能吗?

【问题讨论】:

    标签: colors seaborn


    【解决方案1】:

    非常感谢@Diziet Asahi,这确实适用于示例数据框!但是,在包含更多项目的完整数据框中,我收到错误消息:

    调色板字典缺少键:{'9', '20', ...}

    我猜这是因为 seaborn 中的默认调色板是一个只有十种不同色调的定性调色板。 为了处理这个错误,我设置了以下调色板:

    cmap = sns.color_palette("hls", 75)
    

    这也适用于选择“husl”色彩空间。

    【讨论】:

      【解决方案2】:

      palette=dashes= 可以通过字典映射用于不同颜色/样式的列的级别。

      您可以手动或以编程方式生成这些字典(取决于您有多少级别)。

      例如,调色板:

      #color palette
      cmap = sns.color_palette("bright")
      palette = {key:value for key,value in zip(data[hue_col].unique(), cmap)}
      palette['item_1'] = 'red'
      palette['item_2'] = 'red'
      

      输出:

      {'1': (0.00784313725490196, 0.24313725490196078, 1.0),
      '2': (1.0, 0.48627450980392156, 0.0),
      '3': (0.10196078431372549, 0.788235294117647, 0.2196078431372549),
      'item_1': 'red,
      'item_2': 'red'}
      

      我们为每个级别赋予与“明亮”调色板不同的颜色,如果需要,我们可以手动修复一些值(尽管请记住,明亮调色板中已经有一种与红色非常相似的颜色,所以有可能会造成一些混乱)。

      破折号样式也可以这样做:

      #style palette
      dash_list = sns._core.unique_dashes(data[style_col].unique().size+1)
      style = {key:value for key,value in zip(data[style_col].unique(), dash_list[1:])}
      style['item_1'] = ''  # empty string means solid
      style['item_2'] = ''
      

      输出:

      {'1': (4, 1.5),
      '2': (1, 1),
      '3': (3, 1.25, 1.5, 1.25),
      'item_1': '',
      'item_2': ''}
      

      在这里,我使用 seaborn 的一个私有函数(使用风险自负,可能随时更改),生成破折号样式列表,然后手动设置我想要实线的特定级别。我在dash_list 中请求的项目太多,因为第一个元素始终是实线,我想为item_1item_2 保留实线。

      完整代码:

      data = df
      x_col = 'Flag'
      y_col = "Value"
      hue_col = "Products"
      style_col = "Products"
      
      #color palette
      cmap = sns.color_palette("bright")
      palette = {key:value for key,value in zip(data[hue_col].unique(), cmap)}
      palette['item_1'] = 'red'
      palette['item_2'] = 'red'
      
      
      #style palette
      dash_list = sns._core.unique_dashes(data[style_col].unique().size+1)
      style = {key:value for key,value in zip(data[style_col].unique(), dash_list[1:])}
      style['item_1'] = ''  # empty string means solid
      style['item_2'] = ''
      
      sns.set_theme()
      sns.set_style("ticks")
      sns.set_context("paper")
      
      fig1, ax1 = plt.subplots()
      sns.lineplot(data=df, x=x_col, y=y_col, 
                   hue=hue_col, palette=palette,
                   style=style_col, dashes=style,
                   ax=ax1)
      plt.legend(bbox_to_anchor=(1.02, 1),borderaxespad=0)
      fig1.tight_layout()
      

      【讨论】:

      • 非常感谢@Diziet Asahi,这确实适用于示例数据框!但是,在包含更多项目的完整数据框中,我收到错误消息:调色板字典缺少键:{'9'、'20'、...}。那么,我该如何处理这个错误呢?考虑到我必须分析项目数量不同的数据框。此外,有没有办法为所有名为“item_x”的项目设置线条样式,而不是逐个键入?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多