绘制多个信号的大多数Python方法


问题内容

我想将一个或多个信号绘制到一个图中。

对于每个信号,可以指定单独的颜色,线宽和线型。如果必须绘制多个信号,则还应提供一个图例。

到目前为止,我使用以下代码允许我绘制多达三个信号。

import matplotlib
fig = matplotlib.figure.Figure(figsize=(8,6))
subplot = fig.add_axes([0.1, 0.2, 0.8, 0.75])
Signal2, Signal3, legend, t = None, None, None, None
Signal1, = subplot.plot(xDataSignal1, yDataSignal1, color=LineColor[0], linewidth=LineWidth[0],linestyle=LineStyle[0])
if (yDataSignal2 != [] and yDataSignal3 != []):
    Signal2, = subplot.plot(xDataSignal2, yDataSignal2, color=LineColor[1], linewidth=LineWidth[1],linestyle=LineStyle[1])
    Signal3, = subplot.plot(xDataSignal3, yDataSignal3, color=LineColor[2], linewidth=LineWidth[2],linestyle=LineStyle[2])
    legend = subplot.legend([Signal1, Signal2, Signal3], [yLabel[0], yLabel[1], yLabel[2]],LegendPosition,labelspacing=0.1, borderpad=0.1)
    legend.get_frame().set_linewidth(0.5)
    for t in legend.get_texts():
        t.set_fontsize(10)
elif (yDataSignal2 != []):
    Signal2, = subplot.plot(xDataSignal2, yDataSignal2, color=LineColor[1], linewidth=LineWidth[1],linestyle=LineStyle[1])
    legend = subplot.legend([Signal1, Signal2], [yLabel[0], yLabel[1]], LegendPosition,labelspacing=0.1, borderpad=0.1)
    legend.get_frame().set_linewidth(0.5)
    for t in legend.get_texts():
        t.set_fontsize(10)

是否有可能通过仍然使用matplotlib和subplot来推广该代码,使其更具Python风格并支持多达n个信号?

任何建议,高度赞赏。


问题答案:

字典列表可能是一个很好的解决方案(defaultdict如果您不想指定颜色和线宽,甚至可以使用a来默认它,请在此处阅读更多信息

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

mysignals = [{'name': 'Signal1', 'x': np.arange(10,20,1),
             'y': np.random.rand(10), 'color':'r', 'linewidth':1},
            {'name': 'Signal2', 'x': np.arange(10,20,1),
             'y': np.random.rand(10), 'color':'b', 'linewidth':3},
            {'name': 'Signal3', 'x': np.arange(10,20,1),
             'y': np.random.rand(10), 'color':'k', 'linewidth':2}]

fig, ax = plt.subplots()
for signal in mysignals:
    ax.plot(signal['x'], signal['y'], 
            color=signal['color'], 
            linewidth=signal['linewidth'],
            label=signal['name'])

# Enable legend
ax.legend()
ax.set_title("My graph")
plt.show()

在此处输入图片说明