【问题标题】:Most pythonic way to plot multiple signals绘制多个信号的最pythonic方式
【发布时间】:2017-04-27 11:16:49
【问题描述】:

我想在一张图中绘制一个或多个信号。

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

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

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 个信号?

非常感谢任何建议。

【问题讨论】:

  • 如何创建某种字典列表,其中列表的每个元素都是一个字典,其中包含您的 x 和 y 数据、线条颜色、线条宽度等。然后您可以创建一个情节,迭代所说的dict列表并将所有内容绘制在同一轴上?
  • 好话。我会试试这个。谢谢。

标签: python python-2.7 matplotlib


【解决方案1】:

字典列表可能是一个很好的解决方案(你甚至可以使用defaultdict 来默认颜色和线宽,以防你不想指定它,阅读更多here

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()

【讨论】:

  • 太棒了!非常感谢。
猜你喜欢
  • 1970-01-01
  • 2017-06-17
  • 2023-03-13
  • 2017-11-29
  • 2022-07-02
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多