如何绘制带有图例的非结构化 numpy 数组?

How to plot an unstructured numpy array with a legend?

在使用 matplotlib 绘制 n 维非结构化数组时,是否可以为每个维度生成图例标签?

  • 此示例仅使用二阶 ODE,但应该了解如何添加图例。
  • 通过将 dtype 添加到 sol 数组,将非结构化数组转换为 structured array
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt


# ode system
def pend(y, t, b, c):
    theta, omega = y
    dydt = [omega, -b*omega - c*np.sin(theta)]
    return dydt

b = np.arange(0.50, 0, -0.25)
c = 5.0
y0 = [np.pi - 0.1, 0.0]
t = np.linspace(0, 10, 101)

ls = ['-', '--']  # list of linestyles
count = 0  # used to index the current linestyle
for i in b:
    
    sol = odeint(pend, y0, t, args=(i, c))

    type_to_set = 'float64'  # specify the type you need (e.g. 'float64')
    dtype = np.dtype([(f'{x}_ode:{i}', type_to_set) for x in range(sol.shape[1])])  # create names and dtypes list
    sol_updated = sol.astype(type_to_set).view(dtype)  # add names and dtypes to sol
    
    # plot
    # plt.figure()  # if you want separate plots for each group uncomment this line & put plt.legend in 4 spaces, so it's just after the plotting loop
    for name in sol_updated.dtype.names:
        plt.plot(t, sol_updated[name], linestyle=ls[count], label=name)

    count += 1  # add 1 to the markers indexer
    plt.gca().set_prop_cycle(None)

plt.legend(bbox_to_anchor=(1.04, 0.5), loc='center left', borderaxespad=0)
plt.show()
  • 这是同一图上的 2 组 (101, 2) 数组,每个 ode 解组具有独特的线型。