简体   繁体   中英

plot multiple lines in seaborn lineplot

I'm trying to plot a lineplot with seaborn with following data:

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. Ideally the color differs per model and there are different line styles for y-values.

How do I do that?

IMO, it's a bit of a mess on a single plot, but here we go. You can use one of the default categorial color maps and a dictionary to get a single color for each 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.

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.

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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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