注解
Click here 下载完整的示例代码
刻度之间的标签居中¶
记号标签相对于其关联的记号对齐。可以使用水平对齐属性控制对齐方式“居中”、“左”或“右”:
for label in ax.xaxis.get_xticklabels():
label.set_horizontalalignment('right')
但是,没有直接的方法将标签放在刻度之间居中。要伪造此行为,可以在主刻度之间的次要刻度上放置标签,并隐藏主刻度标签和次要刻度。
下面是一个标记月份的示例,位于刻度之间。

import numpy as np
import matplotlib.cbook as cbook
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
# load some financial data; apple's stock price
r = (cbook.get_sample_data('aapl.npz', np_load=True)['price_data']
.view(np.recarray))
r = r[-250:] # get the last 250 days
fig, ax = plt.subplots()
ax.plot(r.date, r.adj_close)
ax.xaxis.set_major_locator(dates.MonthLocator())
# 16 is a slight approximation since months differ in number of days.
ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=16))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
for tick in ax.xaxis.get_minor_ticks():
tick.tick1line.set_markersize(0)
tick.tick2line.set_markersize(0)
tick.label1.set_horizontalalignment('center')
imid = len(r) // 2
ax.set_xlabel(str(r.date[imid].item().year))
plt.show()
关键词:matplotlib代码示例,codex,python plot,pyplot Gallery generated by Sphinx-Gallery