簡體   English   中英

如何在 matplotlib 中設置 y 軸限制

[英]How can i set the y axis limit in matplotlib

我正在比較兩個不同神經網絡的訓練精度。 我如何設置比例以使它們具有可比性。 (例如將兩個 y 軸都設置為 1,以便圖表具有可比性)

我使用的代碼如下:

 def NeuralNetwork(X_train, Y_train, X_val, Y_val, epochs, nodes, lr):
        hidden_layers = len(nodes) - 1
        weights = InitializeWeights(nodes)
        Training_accuracy=[]
        Validation_accuracy=[]
        for epoch in range(1, epochs+1):
            weights  = Train(X_train, Y_train, lr, weights)
    
            if (epoch % 1 == 0):
                print("Epoch {}".format(epoch))
                print("Training Accuracy:{}".format(Accuracy(X_train, Y_train, weights)))
                
                if X_val.any():
                    print("Validation Accuracy:{}".format(Accuracy(X_val, Y_val, weights)))
                Training_accuracy.append(Accuracy(X_train, Y_train, weights))
                Validation_accuracy.append(Accuracy(X_val, Y_val, weights))
        plt.plot(Training_accuracy) 
        plt.plot((Validation_accuracy),'#008000') 
        plt.legend(["Training_accuracy", "Validation_accuracy"])    
        plt.xlabel("Epoch")
        plt.ylabel("Accuracy")  
        return weights , Training_accuracy , Validation_accuracy

兩張圖如下:

在此處輸入圖片說明

您可以使用fig, ax = plt.subplots(1, 2)構建一個 1 行 2 列的子圖( 參考)。
基本代碼:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(16)
a = np.random.rand(10)
b = np.random.rand(10)

fig, ax = plt.subplots(1, 2)

ax[0].plot(a)
ax[1].plot(b)

plt.show()

在此處輸入圖片說明

如果您設置sharey = 'all'參數,您創建的所有子圖將共享相同的 y 軸比例:

fig, ax = plt.subplots(1, 2, sharey = 'all')

在此處輸入圖片說明

最后,您可以使用ax[0].set_ylim(0, 1)手動設置 y 軸的限制。

全碼:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(16)
a = np.random.rand(10)
b = np.random.rand(10)

fig, ax = plt.subplots(1, 2, sharey = 'all')

ax[0].plot(a)
ax[1].plot(b)

ax[0].set_ylim(0, 1)

plt.show()

在此處輸入圖片說明

嘗試使用 matplotlib.pyplot.ylim(low, high) 參考此鏈接https://www.geeksforgeeks.org/matplotlib-pyplot-ylim-in-python/

暫無
暫無

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

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