【问题标题】:I can't get multiple live plots working at the same time in Matplotlib - Python我无法在 Matplotlib 中同时获得多个实时绘图 - Python
【发布时间】:2018-06-30 23:39:40
【问题描述】:
jsontime = [-9,-8,-7,-6,-5,-4,-3,-2,-1,0]
f, axarr = plt.subplots(1, 1)
ax1 = axarr[0, 0]
ax2 = axarr[0, 1]

def tempa_plot():
    jsontempa = []
    ay=[]
    for k in range(100):
        jsontempaval = random.randint(30, 80)
        jsontempa.append(jsontempaval)
        print(len(jsontempa))

    for i in jsontempa:
        ay.append(i)
        if len(ay) > 10:
            ay.pop(0)
            ax1.ylim(30, 80)  # Set y min and max values
            ax1.xlim(-9, 1)
            ax1.title('Live Streaming Sensor Data: Temperature')
            ax1.grid(True)
            ax1.ylabel('Temp C')  # Set ylabels
            ax1.xlabel('Time')
            ax1.plot(jsontime,ay,label='Degrees C')
            ax1.legend(loc='upper left')  # plot the legend
            ax1.pause(0.2)
            ax1.clf()
            ax1.set_title('Axis [0,0]')

def tempb_plot():
    jsontempb = []
    by=[]
    for k in range(100):
        jsontempaval = random.randint(50, 100)
        jsontempb.append(jsontempaval)
        print(len(jsontempb))

    for i in jsontempb:
        by.append(i)

        if len(by) > 10:
            by.pop(0)
            print(by)
            ax2.ylim(45, 105)  # Set y min and max values
            ax2.xlim(-9, 1)
            ax2.title('Live Streaming Sensor Data: Temperature b')
            ax2.grid(True)
            ax2.ylabel('Temp C')  # Set ylabels
            ax2.xlabel('Time')

            ax2.plot(jsontime,by,label='Degrees C')
            ax2.legend(loc='upper left')  # plot the legend
            ax2.pause(0.2)
            ax2.clf()
            axarr[0, 1].set_title('Axis [0,0]')


tempa_plot()
tempb_plot()

这会引发轴不可下标的错误。 我有来自我的 Arduino 的源源不断的数据流。我应该尝试多线程吗?有没有更简单、更有效的方法来做到这一点?我尝试从不同的程序运行,效果很好。 TIA

【问题讨论】:

    标签: python matplotlib live-streaming


    【解决方案1】:

    plt.subplots(1, 1) 创建一个 1 × 1 的子图网格,即只有一个图。因此,返回的对象是轴本身,而不是数组。我怀疑您正在寻找 plt.subplots(1, 2)plt.subplots(2, 1),具体取决于您希望轴的方向。

    此外,一旦您修复了该问题,您会发现代码中还有其他错误。您似乎将 matplotlib.pyplot (plt) 中的一些函数名称与轴对象上的方法混淆了。例如,要设置 y 限制,您可以使用 plt.ylim(...)axes.set_ylim(...),但不能使用 axes.ylim(...)。我想你在尝试设置ylimxlimtitlexlabelylabel时会遇到这个问题,所有这些都可以通过简单地在每个前面添加set_...来解决属性,如果我没记错的话。

    编辑: 另外,我刚刚注意到您在每个轴上设置了两次标题,第一次不正确,第二次正确;您可能只想这样做一次。也不确定clfpause 调用发生了什么(顺便说一句,这两个调用都需要plt,而不是轴对象)。你应该在调用你的两个函数之后只做plt.show()

    【讨论】:

    • 谢谢!我正在使用 pause 和 clf 进行交互式绘图
    猜你喜欢
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多