matplotlib中具有相同x轴的多个y轴

2024-04-30 11:44:40 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我有几个值要绘制成一个共享相同x轴(时间)但有多个y值(温度、湿度等)的图形,我编写了以下代码。我无法获得正确且形式良好的y轴比例(现在有重叠的y比例,因此您无法真正看到每个值的值)。我想要一个共享同一轴的图形,但y条在右边,你可以理解它的值,所以问题是y条没有很好地显示出来。我怎样才能修好它?这就是问题所在https://i.imgur.com/G1EiYIh.png因为您可以看到y条的形式不好,其中一条也是重叠的

import serial
import time
import matplotlib.pyplot as plt
import numpy as np
from drawnow import *
arduinoData = serial.Serial('/dev/ttyACM0',9600)
time.sleep(2)
data_temperature = []                       # empty list to store the data
data_luminosity = []
data_thermistor = []
data_umidity = []
plt.ion()
counter = 0
def makePlot():

    plt.ylim(15,35)
    plt.title('Real Time Data')
    plt.grid(True)
    plt.ylabel('Temperature')
    plt.plot(data_temperature, 'ro-', label = 'Temperature')
    plt.tick_params(direction='right')
    plt.legend(loc='upper left')
    plt2 = plt.twinx()

    plt2.plot(data_umidity, 'bo-', label = 'Umidity %')
    plt2.legend(loc= 'upper right')
    plt3 = plt.twinx()
    plt3.plot(data_thermistor, 'go-', label = 'Thermistor temperature')
    plt3.legend(loc = 'lower left')


while True:
    if arduinoData.inWaiting()==0:
        pass
    time.sleep(5)
    arduinoString = arduinoData.readline()         # read a byte string
    arrayData = arduinoString.split()
    luminosity = float(arrayData[0])
    thermistorTemperature = float(arrayData[1])
    temperature = float(arrayData[2])
    umidity = float(arrayData[3])
    print(luminosity, thermistorTemperature, temperature, umidity)
    data_temperature.append(temperature)
    data_luminosity.append(luminosity)
    data_thermistor.append(thermistorTemperature)
    data_umidity.append(umidity)
    drawnow(makePlot)
    plt.pause(.000001)
    counter += 1
    if counter > 50:
        data_temperature.pop(0)
        data_umidity.pop(0)


ser.close()


Tags: importdatatimeplotcounterpltfloatlabel
1条回答
网友
1楼 · 发布于 2024-04-30 11:44:40

如果遵循matplotlib example表示多个y轴,并且脊椎不断变化,那么答案就在那里。您需要将其从原始打印中进一步移动,并设置其脊椎的可见性

plt3 = plt.twinx()
# Offset the right spine of plt3.  The ticks and label have already been
# placed on the right by twinx above.
plt3.spines["right"].set_position(("axes", 1.2))
# Having been created by twinx, plt3 has its frame off, so the line of its
# detached spine is invisible.  First, activate the frame but make the patch
# and spines invisible.
make_patch_spines_invisible(plt3)
# Second, show the right spine.
plt3.spines["right"].set_visible(True)

编辑:下面是make_patch_spines_invisible函数,取自上面链接中的示例

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

相关问题 更多 >