使用多条线和色调创建 seaborn 线图

create seaborn lineplot with multiple lines and hue

我有来自多行的数据,我想创建 seaborn lineplot。

每个iteration_value有:

我有这个代码:

def save_graph(properties):
    plt.figure()
    for iteration_values in properties.iteration_values:
        sns_plot = sns.lineplot(iteration_values.x_values, iteration_values.y_values,
                                hue=iteration_values.line_title)

    plt.xlabel = properties.x_label
    plt.ylabel = properties.y_label

    plt.title(properties.title, fontsize=20)
    plt.ylim(0, 1)

    figure.savefig(file_path)

    plt.close()

iteration_values = [GraphIterationValues([1, 2, 3], [0.1, 0.2, 0.3], "first line title"),
                    GraphIterationValues(
                        [1, 2, 3], [0.2, 0.3, 0.4], "second line title"),
                    GraphIterationValues(
                        [1, 2, 3], [0.3, 0.4, 0.5], "third line title"),
                    GraphIterationValues([1, 2, 3], [0.4, 0.5, 0.6], "fourth line title")]

properties = OutputGraphPropertied(
    iteration_values, "x label", "y label", "plot title", "./output.jpeg")
save_graph(properties)

但我收到错误消息:

ValueError: Could not interpret value `first line title` for parameter `hue`

这些是属性 class:

class OutputGraphPropertied:
    def __init__(self, graph_iteration_values, x_label, y_label, title, file_path):
        self.graph_iteration_values = graph_iteration_values
        self.x_label = x_label
        self.y_label = y_label
        self.title = title
        self.file_path = file_path


class GraphIterationValues:
    def __init__(self, x_values, y_values, line_title):
        self.x_values = x_values
        self.y_values = y_values
        self.line_title = line_title

我试图让它看起来像这个带有月份的情节(我用这张图片作为插图):

为了hue正常工作,应立即提供所有数据。此外,hue 应引用与 x 和 y 长度相同的数组,因此重复 x 和 y 值数组中每个条目的行标题。

这里是 save_graph 前几行的可能改编:

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

def save_graph(properties):
    plt.figure()
    x_values = np.concatenate([iteration_values.x_values 
                               for iteration_values in properties.graph_iteration_values])
    y_values = np.concatenate([iteration_values.y_values
                               for iteration_values in properties.graph_iteration_values])
    line_titles = np.concatenate([[iteration_values.line_title] * len(iteration_values.x_values)
                                  for iteration_values in properties.graph_iteration_values])
    sns_plot = sns.lineplot(x=x_values, y=y_values, hue=line_titles)
    ...

另一种选择是在同一张图上绘制多个图,不使用 hue 而是设置 label:

def save_graph(properties):
    plt.figure()
    ax = None
    for iteration_values in properties.iteration_values:
        ax = sns.lineplot(x=iteration_values.x_values, y=iteration_values.y_values,
                                label=iteration_values.line_title, ax=ax)
    ...

这将循环当前颜色循环并创建正确的图例。