pythonpandasplotseabornlinestyle

Specify the linetype for one line in a multiline plot


I'd like to plot a dataframe using standard linestyles and colors for all columns except 1. I would always like my column labeled 'Target' to have linestyle='-.' and be black. I can do this in the plot, but the legend doesn't seem to accept the linetype and uses some default value. Here is the code I'm using, note that "cols_to_plot" is a list containing column names for the data I'm interested in:

fig = plt.figure() 
ax = sns.lineplot(data=df[cols_to_plot])
ax = sns.lineplot(data=df['Target'], linestyle="-.", color='k')
# ax.set_title(title, fontweight='bold')
ax.set_ylabel(y_label)
ax.set_xlabel(x_label)
ax.legend(legend)
fig.tight_layout()
fig.savefig(sv_pth, format='pdf') 

which plots this: Plot with the legend incorrectly labeling the horizontal linetype

Notice that $z^*$ is a solid blue line when infact it should be black with linestyle "-.". I'm sure I'm making a silly mistake, any help is appreciated.


Solution

  • @Suraj Shourie had a good solution, but here's another option I got working:

    fig = plt.figure()
    cols_to_plot = [_ for _ in df.columns if _ not in stats_lst] 
    df_plot = df[cols_to_plot]
    ax = sns.lineplot(data=df_plot)
    idx = len(cols_to_plot) -1
    ax.lines[idx].set_linestyle("-.")
    ax.lines[idx].set_color("black")
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.legend(legend)
    fig.tight_layout()
    fig.savefig(sv_pth, format='pdf') 
    

    I looked into the ax.lines object and found the target (I have to make sure it's the last one added to the plot), then I can set it using the set_linestyle and set_color methods. DB