簡體   English   中英

matplotlib中具有相同x軸的多個y軸

[英]Multiple y axis with same x axes in matplotlib

你好,我有幾個值要繪制成一個共享相同 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()

如果您按照matplotlib 示例獲取多個 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM