简体   繁体   中英

plot label in matplotlib after xy plotting python

I need to create my line label outside of the plotting function for my coordinate points. I have a list of lists to loop through to create separate lines for each phase of test data:

fig = plt.figure(figsize=(11,8.5))
ax = fig.add_subplot(111)    
list_of_x_points = [[1,2,3],[4,5,6,7,8],[9,10,11,12],...]
    list_of_y_points = [[1,1,1],[2,2,2,2,2],[3,3,3,3],...]

for i in range(len(list_of_x_points)):
    ax.plot(list_of_x_points[i], list_of_x_points[i], linecolor = "b" , linewidth = 1, linestyle = 'dashed'))

If I have the label inserted after linestyle , the label will print each time the loop happens. I only want it to print once. I've tried ax.legend(['Line Name']) after and outside of the for loop, but it doesn't work. How can I assign a label to the line in the graph? Graph looks like this:

在此处输入图片说明

As was pointed out, I created a testable version of my code, and the ax.legend() worked.

fig = plt.figure(figsize=(11,8.5))
ax = fig.add_subplot(111)    
list_of_x_points = [[1,2,3],[4,5,6,7,8],[9,10,11,12]]
list_of_y_points = [[1,1,1],[2,2,2,2,2],[3,3,3,3]]

for i in range(len(list_of_x_points)):
    ax.plot(list_of_x_points[i], list_of_x_points[i], "-b" , linewidth = 1, linestyle = 'dashed')
ax.legend(['Print this'])
plt.show()

Still not understanding what was going wrong with my original code, I kept looking and found an obvious answer:

for i in range(len(list_of_x_points)):
    ax.plot(list_of_x_points[i], list_of_x_points[i], "-b" , linewidth = 1, linestyle = 'dashed', label = "Print this" if i == 0 else "")
ax.legend()
plt.show()

I don't know if this is considered bad practice, so I would like some feedback regarding back, but it did work.

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