我的目標是創建一個帶有日期的分層 x 軸。為此,我正在按照此
但是,當我將圖表型別更改為 bar 時ax1.bar(date, data),兩個軸的開始和結束刻度不匹配:

有沒有辦法讓兩個軸在同一點開始和結束?一直延伸第一個軸(不考慮重疊)或調整第二個軸以匹配第一個軸。
uj5u.com熱心網友回復:
為了使兩個 x 軸很好地對齊,重要的是它們具有相同的資料限制 ( ax2.set_xlim(ax1.get_xlim()))。然后,ax2.set_xticks([0, 2.5, 6])將在第一個和最后一個柱的中心以及第三個和第四個柱之間有刻度。
您可以使用ax2.spines['bottom'].set_bounds([0, 6])在這些位置停止 x 軸。
如果你也想隱藏的刻度線ax1,標準的方法是它們的長度設定為零ax1.tick_params(axis='x', length=0)。
如果需要,您還可以隱藏頂部和右側的脊椎。您需要對兩個軸都執行此操作。
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
date = ['2021-01-29', '2021-01-30', '2021-01-31',
'2021-02-01', '2021-02-02', '2021-01-03', '2021-01-04']
day = ['29', '30', '31', '01', '02', '03', '04']
data = [5, 4, 3, 9, 7, 8, 2]
fig, ax1 = plt.subplots(num="TEST")
ax1.bar(date, data)
ax1.set_xticks(np.arange(len(date)))
ax1.set_xticklabels(day)
ax1.margins(x=0)
ax1.tick_params(axis='x', length=0) # hide tick marks
ax2 = ax1.twiny()
ax2.spines['bottom'].set_position(('axes', -0.08))
ax2.tick_params(axis='x', direction='in', which='major')
ax2.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_label_position('bottom')
ax2.set_xlim(ax1.get_xlim()) # same datalimits
ax2.set_xticks([0, 2.5, 6])
ax2.spines['bottom'].set_bounds([0, 6])
ax2.xaxis.set_major_formatter(ticker.NullFormatter())
ax2.xaxis.set_minor_locator(ticker.FixedLocator([1, 4]))
ax2.xaxis.set_minor_formatter(ticker.FixedFormatter(['JAN', 'FEB']))
for ax in (ax1, ax2):
for spine in ['top', 'right']:
ax.spines[spine].set_visible(False)
plt.tight_layout()
plt.show()
除了縮短,set_bounds()還可以延長一點。例如:
ax2.set_xticks([-0.5, 2.5, 6.5])
ax2.spines['bottom'].set_bounds([-0.5, 6.5])

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374528.html
下一篇:如何繪制和注釋分組條
