【问题标题】:How can i set the y axis limit in matplotlib如何在 matplotlib 中设置 y 轴限制
【发布时间】:2021-07-29 06:58:42
【问题描述】:

我正在比较两个不同神经网络的训练精度。如何设置比例以便它们具有可比性。 (比如将两个 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

两张图如下:

【问题讨论】:

  • 如果你使用子图你也可以写sharey=True

标签: python matplotlib plot graph subplot


【解决方案1】:

您可以使用fig, ax = plt.subplots(1, 2) 构建一个具有 1 行和 2 列的子图 (reference)。

基本代码

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

【讨论】:

    【解决方案2】:

    尝试使用 matplotlib.pyplot.ylim(low, high) 参考这个链接https://www.geeksforgeeks.org/matplotlib-pyplot-ylim-in-python/

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 2012-04-22
      • 2020-06-30
      • 1970-01-01
      相关资源
      最近更新 更多