简体   繁体   中英

How to recursively adding a line of code for plot text with given a given condition

So, from this graph below, I find discrete points and their indexes. When we draw a final figure, the figure should have the information of when is the exact time that discontinuity happened and vertical line at the discontinuity should be added. In order to do that, I had to add "plt.axvline" and "plt.text" together as a pair.

带断点的图表

I wrote out the code like this here:

However, whenever new index comes, it's very inconvenient to add two lines of code manually, and what if 100 discontinuities manifested than it's almost nearly impossible to add them.

I am thinking of object oriented method for this like "class" but I have no idea where to start..

Any idea of how to recursively adding it with knowing length of indexes?

if len(idx) == 1 :     
    plt.figure(figsize = (20,10))
    plt.axvline(x=idx[0], color = 'r')
    plt.text(idx[0],.13, '{}'.format(send_time[idx[0]-1]))
    plt.title(var)
    plt.scatter(x, result, alpha = alp)
    plt.savefig("XXX.png")
    plt.close()
elif len(idx) == 2:
    plt.figure(figsize = (20,10))
    plt.axvline(x=idx[0], color = 'r')
    plt.text(idx[0],.10, '{}\n{}'.format(send_time[idx[0]], time1[idx[0]]))
    plt.axvline(x=idx[1], color = 'b')
    plt.text(idx[1],.10, '{}'.format(send_time[idx[1]-1]))
    plt.title(var)
    plt.scatter(x, result, alpha = alp)
    plt.savefig("XXX.png")
    plt.close()
elif len(idx) == 3:
    plt.figure(figsize = (20,10))
    plt.axvline(x=idx[0], color = 'r')
    plt.text(idx[0],.13, '{}\n{}'.format(send_time[idx[0]],time1[idx[0]]))
    plt.axvline(x=idx[1], color = 'b')
    plt.text(idx[1],.12, '{}\n{}'.format(send_time[idx[1]],time1[idx[1]]))
    plt.axvline(x=idx[2], color = 'y')
    plt.text(idx[2],.11, '{}'.format(send_time[idx[2]-1]))
    plt.title(var)
    plt.scatter(x, result, alpha = alp)
    plt.savefig("XXX.png")
    plt.close()

In general, it's better to loop over a collection directly for item in collection rather than using indices.

plt.figure(figsize = (20,10))
for num in idx:
    plt.axvline(num, color = 'r')
    plt.text(num, .13, '{}'.format(send_time[num-1]))
plt.title(var)
plt.scatter(x, result, alpha = alp)
plt.savefig("XXX.png")
plt.close()

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