deblue
deblue

Reputation: 267

Updating pyplot legend within a loop

I am trying to add a an entry to the legends every time the loop iterates. a and b are str and I would like to somehow update the legends within the loop, that way it would plt.plot them and update the legends given a and b. Is there any way I can do this? Thanks!

plt.figure(figsize=(8.5, 4.5))
for a,b in zip(assets,buckets):
    df_temp = pd.read_excel(filename, sheet_name = a)
    df_temp = df_temp[['SPOT', b]]
    df_temp.dropna(inplace=True)
    df_temp_change = np.log(df_temp.values[:-1] / df_temp.values[1:])
    x1 = df_temp_change[:,0]
    x2 = df_temp_change[:,1]
    t_corr_vectors = threshold_corr(x1, x2, q_ts)
#    t_corr_vectors1 = threshold_corr(x1, x2, q_ts1)
#    t_corr_vectors2 = threshold_corr(x1, x2, q_ts2)
    plt.plot(q_ts, t_corr_vectors)
    plt.legend((t_corr_vectors),(a + "-" + b))
plt.title("Threshold Correlations")
plt.ylabel("Correlations")
plt.xlabel("Quantiles")
plt.savefig("TEST.jpg")

Upvotes: 0

Views: 389

Answers (1)

Andrea
Andrea

Reputation: 3077

You can set the label inside the plot function, and then activate the legend at the end:

plt.figure(figsize=(8.5, 4.5))
for a,b in zip(assets,buckets):
    df_temp = pd.read_excel(filename, sheet_name = a)
    df_temp = df_temp[['SPOT', b]]
    df_temp.dropna(inplace=True)
    df_temp_change = np.log(df_temp.values[:-1] / df_temp.values[1:])
    x1 = df_temp_change[:,0]
    x2 = df_temp_change[:,1]
    t_corr_vectors = threshold_corr(x1, x2, q_ts)
#    t_corr_vectors1 = threshold_corr(x1, x2, q_ts1)
#    t_corr_vectors2 = threshold_corr(x1, x2, q_ts2)
    plt.plot(q_ts, t_corr_vectors, label=(a + "-" + b))
plt.legend()
plt.title("Threshold Correlations")
plt.ylabel("Correlations")
plt.xlabel("Quantiles")
plt.savefig("TEST.jpg")

Upvotes: 1

Related Questions