How can I set the y axis limit?

Question:

I am comparing the training accuracies of two different neural networks. How can I set the scales so that they are comparable. (like setting both y axis to 1 for both so that the graphs are comparable)

The code I used is below:

 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

and the two graphs are as below :

enter image description here

Asked By: user157522

||

Answers:

try use matplotlib.pyplot.ylim(low, high) refer this link https://www.geeksforgeeks.org/matplotlib-pyplot-ylim-in-python/

Answered By: Sai Chandra Reddy

You could use fig, ax = plt.subplots(1, 2) to build a subplot with 1 row and 2 columns (reference).

Basic Code

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

enter image description here

If you set sharey = 'all' parameter, all subplots you created will share the same scale for y axis:

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

enter image description here

Finally, you can manually set limits for y axis with ax[0].set_ylim(0, 1).

Complete Code

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

enter image description here

Answered By: Zephyr