简体   繁体   中英

How to create legends with matplotlib in a loop in Python?

I'm creating a graph with matplotlib in Python using a loop. The loop go trough a dictionary dict_df containing several data frames (keys are df1 , df2,...). The number of data frames, and therefore the number of legends, is not fixed. Each data frame is really simple: they contain 2 columns, and all data frame must be plotted in the same graph:

fig = plt.figure(figsize=(10,5))
plt.grid(True)

m = 1
while m < i:
    plt.plot((dict_df[str("df")+str(m)])["Turns Adjusted"],(dict_df[str("df")+str(m)])["Torque Adjusted"])
    m = m + 1

plt.show()

The plot shows the the graph correctly, but I don't know how to add legends or label for each data frame, using the same loop.

Can anyone help? Thank you!

Try adding the argument label='...' to your calls of plt.plot , and add plt.legend() in the end after the loop and before 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