如何在 Python 中创建具有不同行样式的主要和次要网格线

我目前正在使用 matplotlib.pyplot来创建图形,并希望有坚实和黑色的主要网格线和次要的灰色或虚线。

在网格属性中,which=both/major/mine,然后颜色和线条样式由线条样式简单地定义。有没有办法只指定次要线条样式?

到目前为止,我的合适代码是

plt.plot(current, counts, 'rd', markersize=8)
plt.yscale('log')
plt.grid(b=True, which='both', color='0.65', linestyle='-')
209646 次浏览

一个简单的 DIY 方法就是自己做网格:

import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(111)


ax.plot([1,2,3], [2,3,4], 'ro')


for xmaj in ax.xaxis.get_majorticklocs():
ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
ax.axvline(x=xmin, ls='--')


for ymaj in ax.yaxis.get_majorticklocs():
ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
ax.axhline(y=ymin, ls='--')
plt.show()

实际上,这很简单,就是分别设置 majorminor:

In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]


In [10]: yscale('log')


In [11]: grid(b=True, which='major', color='b', linestyle='-')


In [12]: grid(b=True, which='minor', color='r', linestyle='--')

小网格的陷阱是你必须打开小刻度标记。在上面的代码中,这是由 yscale('log')完成的,但也可以用 plt.minorticks_on()完成。

enter image description here