【问题标题】:How to deal with for-loops in plotting multiple graph in the same plot?如何在同一图中绘制多个图时处理 for 循环?
【发布时间】:2018-03-26 15:55:04
【问题描述】:

模板程序可以工作,但缺点是 plot() 的行数很多。如何用有效的 for 循环替换 6 行 plot()? 我将如何处理索引和标签?

    """
    # Import
    import matplotlib.pyplot as plt

    # Experimental data
    y_data = []
    y_data.append([21.2, 32.5, 42.1, 54.5, 23.5])
    y_data.append([17.2, 27.6, 35.7, 45.8, 27.1])
    y_data.append([25.7, 34.1, 34.7, 50.3, 31.3])
    y_data.append([11.2, 32.5, 45.1, 54.5, 23.5])
    y_data.append([27.4, 25.6, 45.7, 37.8, 25.1])
    y_data.append([23.4, 22.1, 54.7, 45.3, 19.3])

    # For x-axis
    x_data = range(1, len(y_data[1])+1)

    # %% Repetitve use of plot 
    # The following code plots the data but is repetitive 
    #
    fig1 = plt.figure()
    plt.plot(x_data, y_data[0], label='Expt on 31-01-18')
    plt.plot(x_data, y_data[1], label='Expt on 02-02-18')
    plt.plot(x_data, y_data[2], label='Expt on 05-02-18')
    plt.plot(x_data, y_data[3], label='Expt on 07-02-18')
    plt.plot(x_data, y_data[4], label='Expt on 10-02-18')
    plt.plot(x_data, y_data[5], label='Expt on 17-02-18')
    plt.legend()
    plt.xlabel('input')
    plt.ylabel('output')
    plt.grid()
    plt.show()

【问题讨论】:

  • 什么模板程序?请显示您尝试运行的代码。
  • 请勿使用问题图片,将文字内容复制到问题本身,方便我们为您提供帮助。
  • 抱歉,已修复!

标签: python python-3.x for-loop indexing


【解决方案1】:

你可以按顺序计算的项目,你编码成循环序列。 不规则变化的项目,你放入一个列表。 您已经拥有这种数据技术;只需将其扩展到标签即可。

label_list = [
    'Expt on 31-01-18',
    'Expt on 02-02-18',
    'Expt on 05-02-18',
    'Expt on 07-02-18',
    'Expt on 10-02-18',
    'Expt on 17-02-18'
]
for plot_num in range(6):
    plt.plot(x_data, y_data[plot_num], label=label_list[plot_num])

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多