简体   繁体   English

plot seaborn 线图中的多条线

[英]plot multiple lines in seaborn lineplot

I'm trying to plot a lineplot with seaborn with following data:我正在尝试使用 seaborn 与以下数据 plot 线图:

model   K   precision   recall  f1
modelX  5   0.70        0.36    0.48
modelX  10  0.62        0.62    0.62
modelX  20  0.39        0.77    0.51
ModelY  5   0.73        0.37    0.5
ModelY  10  0.64        0.64    0.64
ModelY  20  0.4         0.8     0.5

K represents the x-axis and precision , recall , and f1 should be the values for the y-axis. K代表 x 轴, precisionrecallf1应该是 y 轴的值。 Ideally the color differs per model and there are different line styles for y-values.理想情况下,每个 model 的颜色不同,并且 y 值有不同的线 styles。

How do I do that?我怎么做?

IMO, it's a bit of a mess on a single plot, but here we go. IMO,在单个 plot 上有点乱,但这里是 go。 You can use one of the default categorial color maps and a dictionary to get a single color for each model.您可以使用默认类别颜色图之一和字典为每个 model 获取单一颜色。 You can use groupby to plot each model separately and knowing there are 3 lines for each we can plan to cycle the linestyles to achieve different linestyles for each of the columns.您可以分别使用groupby到 plot 每个 model 并且知道每个有 3 行我们可以计划循环线条样式以实现每列的不同线条样式。

The default legend will be total garbage, so we can construct it ourselves to indicate what model each color represents and what linestyle is used for each measurement.默认图例将是总垃圾,因此我们可以自己构建它以指示每种颜色代表什么 model 以及每次测量使用什么线型。

import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.lines import Line2D

colors = dict(zip(df.model.unique(), plt.cm.tab10.colors))
linestyles = ["-", "--", "-."]
ycols = ['precision', 'recall', 'f1']

# Construct legend ourself
legend_elements = ([Patch(facecolor=color, label=model)
                    for model,color in colors.items()]
                   + [Line2D((0,1),(0,0), color='black', linestyle=linestyle, label=col)
                     for linestyle,col in zip(linestyles, ycols)])
 
fix, ax = plt.subplots()
ax.set_prop_cycle(plt.cycler('linestyle', linestyles))
for model, gp in df.groupby('model'):
    gp.plot(x='K', y=ycols,
            ax=ax,
            color=colors[model],
            legend=False)

ax.legend(handles=legend_elements, bbox_to_anchor=(1,1))
plt.show()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM