简体   繁体   中英

How to put a text box on python figure when the xaxis is a datetime

I have made a figure with the x-axis as datetime (2012-8-1, 2012-10,7....)

I want to put a textbox to label this figure

id = ("(A)","(B)","(C)","(D)","(E)","(Average)")

X-axis

months = mpl.dates.MonthLocator() # every month
days = mpl.dates.DayLocator(interval=5) # every 10 days
dateFmt=mpl.dates.DateFormatter('%m-%d')    
ax.xaxis.set_major_formatter(dateFmt)
ax.xaxis.set_major_locator(months)
#ax.xaxis.set_minor_locator(days)
ax.xaxis_date()

Y-axis

ax.set_ylim(ymin[i],ymax[i])
ax.set_ylabel(ylabels)
ax.axhline(linewidth=0.5,color="k")
ax.yaxis.set_major_locator(tk.MaxNLocator(nbins=3))
ax.yaxis.set_minor_locator(tk.MaxNLocator(nbins=6))
[tickline.set_markersize(3) for tickline in ax.yaxis.get_ticklines(minor=True)]
[tickline.set_markersize(2.5) for tickline in ax.yaxis.get_ticklines(minor=True)]

Text

ax.text(0.25,ymax[i],id[i],fontsize=15)

But I can't see the labels at all.

How can I realize it?

You need to either enter the x-coordinate in the same format (a date) as for the other plot methods, or transform the coordinates. If you want to stick with the x=.25 you could use:

ax.text(0.25,ymax[i],id[i], transform=ax.transAxes, fontsize=15)

It will place the text at a quarter of the ax's width.

An approach is to convert the date to a number and use the number in subsequent calls:

dates = matplotlib.dates.date2num([x])
ax.text(dates[0], y, message, color='red')

where x is the datetime you want to convert, y is assumed not to be in datetime format but in numerical format, and message contains the string you want to have displayed.

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