python - 在 matplotlib 中使用绘图、轴或图形绘制绘图有什么区别?

标签 python matplotlib

当我在 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 个方法中的任何一个时,幕后会发生什么?
  • 什么时候应该使用哪种方法,在这些方法上使用 any 的利弊是什么?
  • 最佳答案

    方法一

    plt.plot(x, y)
    

    这使您可以仅绘制一个具有 (x,y) 坐标的图形。如果你只想得到一个图形,你可以使用这种方式。

    方法二
    ax = plt.subplot()
    ax.plot(x, y)
    

    这使您可以在同一窗口中绘制一个或多个图形。在编写它时,您将只绘制一个图形,但您可以制作如下内容:
    fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    

    您将绘制 4 个名为 ax1、ax2、ax3 和 ax4 的图形,每个图形都在同一窗口上。在我的示例中,这个窗口将被分为 4 个部分。

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

    我没有使用它,但您可以找到文档。

    示例:
    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

    其他示例:

    enter image description here

    关于python - 在 matplotlib 中使用绘图、轴或图形绘制绘图有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37970424/

    相关文章:

    python - 需要在图表外使用 matplotlib 散点标记,在条形图的标签中

    python - 将 DataFrame 的列绘制为针对相同 y 列的散点图

    python - 属性错误 : 'str' object has no attribute 'slice'

    python - python中的正则表达式似乎没有像我期望的那样工作

    python - 有没有办法在单个查询中获取表行和表数据的总数

    python : plots with different line styles having the same legend

    python - Matplotlib Stackplot 图例错误

    Python getattr() 以另一个属性作为默认值

    python - 没有模块名册

    python - Pandas 跳过 x 刻度标签