<p>记号位置定义栅格的位置。所以,在x方向上,我们每10个就有一个。标签可以设置为空字符串,第一个和最后一个除外</p>
<p>最复杂的部分是强制第一条和最后一条网格线可见。由于成圆,有时它们可能落在绘图区域之外。在限制中添加一个额外的ε,应强制这些网格线可见</p>
<p>x和Y标签的填充可以设置为负数,以使它们更靠近轴</p>
<p>请注意,图形和轴应在执行设置标签和轴网等操作之前创建。最简单的方法是在任何打印相关命令之前调用<code>fig, ax = plt.subplots()</code></p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
# create some dummy data
x = np.linspace(0, 60, 500)
y = (np.sin(x / 5) + 1) * 450000 / 2
fig, ax1 = plt.subplots(figsize=(6, 4.4))
ax1.plot(x, y, color='#696969', linewidth='0.5')
xlims = (0, 60)
xlim_eps = xlims[1] / 200
# use some extra epsilon to force the first and last gridline to be drawn in case rounding would put them outside the plot
ax1.set_xlim(xlims[0] - xlim_eps, xlims[1] + xlim_eps)
xticks = range(xlims[0], xlims[1] + 1, 10)
ax1.set_xticks(xticks) # the ticks define the positions for the grid
ax1.set_xticklabels([i if i in xlims else '' for i in xticks]) # set empty label for all but the first and last
ax1.set_xlabel("Time [sec]", labelpad=-8) # negative padding to put the label closer to the axis
ylims = (0, 450)
ylim_eps = ylims[1] / 200
ax1.set_ylim(ylims[0] - ylim_eps, ylims[1] + ylim_eps)
yticks = range(ylims[0], ylims[1] + 1, 50)
ax1.set_yticks(yticks)
ax1.set_yticklabels([f'{i:.3f}' if i in ylims else '' for i in yticks])
ax1.tick_params(axis='y', rotation=90)
ax1.set_ylabel("Load [kN]", labelpad=-8)
ax1.grid(True, linestyle='dotted')
for dir in ['right', 'bottom', 'left', 'top']:
ax1.spines[dir].set_color('none')
ax1.tick_params(axis='both', which='major', labelsize=6, colors='#696969', length=0)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/rT5qi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rT5qi.png" alt="enter image description here"/></a></p>