我目前正在使用matplotlib.pyplot
创建图表,并希望主要网格线为实线和黑色,而较小的网格线为灰色或虚线。
在网格属性中,which=both/major/mine
,然后颜色和线条样式仅由linestyle定义。有没有办法只指定次要的线型?
我到目前为止的相应代码是
plt.plot(current, counts, 'rd', markersize=8)
plt.yscale('log')
plt.grid(b=True, which='both', color='0.65', linestyle='-')
答案 0 :(得分:150)
实际上,它就像分别设置major
和minor
一样简单:
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()
完成。
答案 1 :(得分:20)
一种简单的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()