如何在Python中创建具有不同线型的主网格线和次网格线

2024-04-26 22:41:36 发布

您现在位置: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='-')

Tags: 图形网格which属性matplotlibplt虚线黑色
2条回答

实际上,只需分别设置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

一个简单的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()

相关问题 更多 >