为什么仅在最后一个子图上打开网格?

时间:2020-02-01 18:44:54

标签: python-3.x matplotlib jupyter-notebook anaconda widget

我在函数中使用子图,该函数使用滑块控件输入来计算一些内容并绘制结果。 我想为ax1的所有子图打开网格。但是不知何故,jupternotebooks仅在最后一个情节上将其打开...

import numpy as np
from matplotlib import pyplot as plt
import ipywidgets as widgets
from IPython.html.widgets import interact
%matplotlib inline

## Plot 
fig, ax1 = plt.subplots(6,2)
plt.subplots_adjust(right = 2, top = 8 )
# Show the major grid lines with dark grey lines
plt.grid(b=True, which='major', color='#666666', linestyle='-')
# Show the minor grid lines with very faint and almost transparent grey lines
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)

## Giergeschwindigkeit über v und ay
ax1[0,0].plot(v_ms, omega)
ax1[0,0].set_ylabel('Giergeschwindigkeit [rad/s]')
ax1[0,0].set_xlabel('Geschwindigkeit [m/s]')
ax1[0,0].set_title('Giergeschwindigkeit über Geschwindigkeit')
# ... more subplots
plt.show()

它看起来像这样: enter image description here

您能向我解释为什么是我的情况

ax1.grid()

抛出错误?

AttributeError: 'numpy.ndarray' object has no attribute 'grid'

1 个答案:

答案 0 :(得分:5)

这是因为plt仅对最后创建的axis对象起作用。
而且您收到该错误的原因是ax1是一个numpy n维数组,而不是axis对象。

您可以执行以下操作以遍历numpy n维数组以创建网格:

for row in axes: 
    for ax in row: 
        ax.grid(b=True, which='major', color='#666666', linestyle='-')
        ax.minorticks_on()  
        ax.grid(b=True, which='minor', color='#999999', linestyle='-',alpha=0.2)  

结果(无plt.subplots_adjust()): enter image description here