【问题标题】:Why is the grid turned on only on the last subplot?为什么网格只在最后一个子图上打开?
【发布时间】:2020-05-18 01:52:50
【问题描述】:

我在一个函数中使用子图,该函数使用滑块小部件输入来计算一些东西并绘制结果。 我想为 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()

看起来像这样:

你能告诉我为什么在我的情况下

ax1.grid()

抛出错误?

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

【问题讨论】:

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


    【解决方案1】:

    这是因为plt 只会对最后创建的坐标区对象进行操作。
    您收到该错误的原因是 ax1 是一个 numpy n 维数组,而不是轴对象。

    您可以这样做来迭代 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()):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      相关资源
      最近更新 更多