【问题标题】:Indexing single dimensional Axes array with two indices [duplicate]用两个索引索引一维轴数组[重复]
【发布时间】:2021-04-15 06:54:12
【问题描述】:

我想写一个绘制图表的公式。我有这样的数据

import numpy as np
import matplotlib.pyplot as plt

x = (['2020-08-01', '2020-09-01', '2020-08-01'])
y = ([1,3, 8])

我的公式是

def fire_m(x,y, i,j):
    ax[i,j].plot(x, y)

当我这样做时

fig, ax = plt.subplots(3,2)
fire_m(x, y, 0, 0)
plt.show()

没关系。但如果我只需要一列

fig, ax = plt.subplots(3,1)
    fire_m(x, y, 0, 0)
    plt.show()

我明白了

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

我努力改进

def fire_m(x,y, i,j=np.nan):
        ax[i,j].plot(x, y)

但这是不正确的。如何解决?

【问题讨论】:

  • 您所说的“公式”通常称为“函数”供参考
  • 您可以将squeeze=False 添加到plt.subplots(...., squeeze=False) 以始终拥有二维轴。

标签: python matplotlib subplot


【解决方案1】:

如果你想使用nan 作为解决方法,你可以试试这个:

def fire_m(x, y, i, j=np.nan):
    if j == np.nan:
        ax[i].plot(x, y)
    else:
        ax[i,j].plot(x, y)

另一种选择是使用numpy.ravel_multi_index。这会将i, j-坐标转换为扁平版本数组中的单个索引。

def fire_m(x, y, i, j):
    n = np.ravel_multi_index([i, j], ax.shape)
    ax.flatten()[n].plot(x, y)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2019-11-18
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多