<p>问题如下。<code>pd.date_range(start='4/1/2012', periods=len(y1))</code>创建从2012年4月1日到2012年7月9日的日期。<br/>
现在将主定位器设置为<code>YearLocator</code>。这意味着,您希望在轴上每年都有一个记号。但是,所有日期都在2012年的同一年内。因此在绘图范围内没有显示主要刻度。你知道吗</p>
<p>建议改为使用<code>MonthLocator</code>,这样每个月的第一个就被勾选。另外,如果使用格式设置器是有意义的,它实际上显示月份,例如<code>'%b %Y'</code>。如果您愿意,您可以使用<code>DayLocator</code>作为小记号来显示每天的小记号。你知道吗</p>
<pre><code>ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.xaxis.set_minor_locator(mdates.DayLocator())
</code></pre>
<p>完整示例:</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
y1 = np.arange(100)*0.14+1
y2 = -(np.arange(100)*0.04)+12
x = pd.date_range(start='4/1/2012', periods=len(y1))
fig, ax = plt.subplots()
ax.plot(x,y1)
ax.plot(x,y2)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.xaxis.set_minor_locator(mdates.DayLocator())
fig.autofmt_xdate()
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/5gp4j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5gp4j.png" alt="enter image description here"/></a></p>