首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在函数中使用两个不同的y变量在同一页上创建两个独立的图

在函数中使用两个不同的y变量在同一页上创建两个独立的图,可以通过使用不同的图形对象或子图来实现。

  1. 使用不同的图形对象: 可以使用matplotlib库创建两个不同的图形对象,并在每个对象中绘制相应的图形。以下是一个示例代码:
代码语言:txt
复制
import matplotlib.pyplot as plt

def create_two_independent_plots():
    x = [1, 2, 3, 4, 5]

    # 创建第一个图形对象
    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111)
    y1 = [1, 4, 9, 16, 25]
    ax1.plot(x, y1)
    ax1.set_title('Plot 1')

    # 创建第二个图形对象
    fig2 = plt.figure()
    ax2 = fig2.add_subplot(111)
    y2 = [1, 8, 27, 64, 125]
    ax2.plot(x, y2)
    ax2.set_title('Plot 2')

    # 显示图形
    plt.show()

create_two_independent_plots()
  1. 使用子图: 通过matplotlib的subplot函数,可以在同一个图形对象中创建多个子图,并在每个子图中绘制相应的图形。以下是一个示例代码:
代码语言:txt
复制
import matplotlib.pyplot as plt

def create_two_independent_plots():
    x = [1, 2, 3, 4, 5]

    # 创建图形对象和子图
    fig, (ax1, ax2) = plt.subplots(2, 1)

    # 在第一个子图中绘制图形
    y1 = [1, 4, 9, 16, 25]
    ax1.plot(x, y1)
    ax1.set_title('Plot 1')

    # 在第二个子图中绘制图形
    y2 = [1, 8, 27, 64, 125]
    ax2.plot(x, y2)
    ax2.set_title('Plot 2')

    # 调整子图间的间距
    plt.tight_layout()

    # 显示图形
    plt.show()

create_two_independent_plots()

以上两种方法都能实现在同一页上创建两个独立的图形,选择使用哪种方法取决于具体的需求和个人喜好。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券