-1

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.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
derekboase
  • 56
  • 6

2 Answers2

2

Thanks for updating the question, you can do this using matplotlib.pyplot, not sure how to do this using seaborn (maybe there is an elegant solution which I am missing):

import matplotlib.pylab as plt
df = pd.DataFrame( { "col1" : np.random.rand(10), "col2": np.random.rand(10), "col3": np.array([1]*10) })
cols = ["col1", "col2", ]
for col in cols:
    plt.plot(df.index, df[col], label = col)
plt.plot(df.index, df["col3"], label = "Target", linestyle = "-.", color = "k")
plt.ylim(0,1.2)
plt.legend()
plt.show()

PLt

Suraj Shourie
  • 536
  • 2
  • 11
  • Great suggestion. I'm a bit stubborn so I'd like to figure it out using seaborn, but this is definitely a good answer. I'll edit my question with what I got working (it's a bit of a hack solution). Thanks mate! – derekboase Aug 02 '23 at 19:22
  • Gotcha, I added it. – derekboase Aug 02 '23 at 19:28
1

@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

derekboase
  • 56
  • 6