首页 文章

使用matplotlib中的绘图,轴或图形绘制绘图有什么区别?

提问于
浏览
42

当我在matplotlib中绘制情节时,我有点困惑后端的情况,tbh,我不清楚情节,轴和图的层次结构 . 我阅读了文档,这很有帮助,但我仍然感到困惑......

以下代码以三种不同的方式绘制相同的图表 -

#creating the arrays for testing
x = np.arange(1, 100)
y = np.sqrt(x)
#1st way
plt.plot(x, y)
#2nd way
ax = plt.subplot()
ax.plot(x, y)
#3rd way
figure = plt.figure()
new_plot = figure.add_subplot(111)
new_plot.plot(x, y)

现在我的问题是 -

  • 三者之间有什么区别,我的意思是当调用3种方法中的任何一种时,底层是什么?

  • 应该使用哪种方法何时以及使用任何方法的利弊是什么?

1 回答

  • 21

    Method 1

    plt.plot(x, y)
    

    这使您可以使用(x,y)坐标绘制一个图形 . 如果您只想获得一个图形,可以使用这种方式 .

    Method 2

    ax = plt.subplot()
    ax.plot(x, y)
    

    这使您可以在同一窗口中绘制一个或多个图形 . 当你写它时,你只会绘制一个数字,但你可以做这样的事情:

    fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    

    您将在同一窗口上绘制4个数字,这些数字分别命名为ax1,ax2,ax3和ax4 . 这个窗口将用我的例子分为4个部分 .

    Method 3

    fig = plt.figure()
    new_plot = fig.add_subplot(111)
    new_plot.plot(x, y)
    

    我没有使用它,但你可以找到文档 .

    Example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # Method 1 #
    
    x = np.random.rand(10)
    y = np.random.rand(10)
    
    figure1 = plt.plot(x,y)
    
    # Method 2 #
    
    x1 = np.random.rand(10)
    x2 = np.random.rand(10)
    x3 = np.random.rand(10)
    x4 = np.random.rand(10)
    y1 = np.random.rand(10)
    y2 = np.random.rand(10)
    y3 = np.random.rand(10)
    y4 = np.random.rand(10)
    
    figure2, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    ax1.plot(x1,y1)
    ax2.plot(x2,y2)
    ax3.plot(x3,y3)
    ax4.plot(x4,y4)
    
    plt.show()
    

    enter image description here

    enter image description here

    Other example:

    enter image description here

相关问题