在刻度之間居中標籤#

刻度標籤會相對於其相關聯的刻度對齊。可以使用水平對齊屬性來控制對齊方式「居中」、「靠左」或「靠右」

但是,沒有直接的方法可以在刻度之間居中標籤。若要模擬此行為,可以在主要刻度之間的中間次要刻度上放置標籤,並隱藏主要刻度標籤和次要刻度。

以下範例會標示月份,並使其在刻度之間居中。

centered ticklabels
import matplotlib.pyplot as plt

import matplotlib.cbook as cbook
import matplotlib.dates as dates
import matplotlib.ticker as ticker

# Load some financial data; Google's stock price
r = cbook.get_sample_data('goog.npz')['price_data']
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'))

# Remove the tick lines
ax.tick_params(axis='x', which='minor', tick1On=False, tick2On=False)

# Align the minor tick label
for label in ax.get_xticklabels(minor=True):
    label.set_horizontalalignment('center')
imid = len(r) // 2
ax.set_xlabel(str(r["date"][imid].item().year))
plt.show()

腳本的總執行時間: (0 分鐘 1.010 秒)

由 Sphinx-Gallery 產生的圖庫