python - Matplotlib:如何绘制列表中的数据,添加两个 y 轴?

标签 python numpy matplotlib plot multiple-axes

我需要用matplotlib生成一些图,但我对此很差。我有五个 列表,每个列表包含 100 值。它们的值因以下因素而异:

enter image description here

我希望能够生成两个line-and-marker图表:

  1. 第一个图涉及列表 1、2、3 和 4,并具有两个 y 轴。列表 1、2 和 3 依赖于常规 y 轴,而列表 4 依赖于添加的 y 轴,如下所示:

enter image description here

  • 第二个必须仅绘制列表 4 和 5,但使用常规 y 轴。
  • 在继续之前,我需要将每个列表转换为numpy数组吗?不管怎样,我没能弄清楚如何使用 matplotlib 进行绘图。任何帮助都感激不尽。谢谢!

    最佳答案

    你只需要创建一个 twinx在单独的 y 轴上绘制 list 4 的坐标轴。你可以看一个例子here .

    这是一个简短的脚本来完成您想要的操作。在这种情况下,无需转换为 numpy 数组。

    import matplotlib.pyplot as plt
    
    # Some sample lists
    l1 = [0.7,0.8,0.8,0.9,0.8,0.7,0.6,0.9,1.0,0.9]
    l2 = [0.2,0.3,0.1,0.0,0.2,0.1,0.3,0.1,0.2,0.1]
    l3 = [0.4,0.6,0.4,0.5,0.4,0.5,0.6,0.4,0.5,0.4]
    
    l4 = [78,87,77,65,89,98,74,94,85,73]
    l5 = [16,44,14,55,34,36,76,54,43,32]
    
    # Make a figure
    fig = plt.figure()
    
    # Make room for legend at bottom
    fig.subplots_adjust(bottom=0.2)
    
    # The axes for your lists 1-3
    ax1 = fig.add_subplot(211)
    # A twin axis for list 4. This shares the x axis, but has a separate y axis
    ax2 = ax1.twinx()
    
    # Plot lines 1-3
    line1 = ax1.plot(l1,'bo-',label='list 1')
    line2 = ax1.plot(l2,'go-',label='list 2')
    line3 = ax1.plot(l3,'ro-',label='list 3')
    
    # Plot line 4
    line4 = ax2.plot(l4,'yo-',label='list 4')
    
    # Some sensible y limits
    ax1.set_ylim(0,1)
    ax2.set_ylim(0,100)
    
    # Your second subplot, for lists 4&5
    ax3 = fig.add_subplot(212)
    
    # Plot lines 4&5
    ax3.plot(l4,'yo-',label='list 4')
    line5 = ax3.plot(l5,'mo-',label='list 5')
    
    # To get lines 1-5 on the same legend, we need to 
    # gather all the lines together before calling legend
    lines = line1+line2+line3+line4+line5
    labels = [l.get_label() for l in lines]
    
    # giving loc a tuple in axes-coords. ncol=5 for 5 columns
    ax3.legend(lines, labels, loc=(0,-0.4), ncol=5)
    
    ax3.set_xlabel('events')
    
    # Display the figure
    plt.show()
    

    enter image description here

    关于python - Matplotlib:如何绘制列表中的数据,添加两个 y 轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690727/

    相关文章:

    python - 使用AWS cloudformation启动EC2实例时如何知道实例已准备好

    python - 如何在没有 NaN 的情况下组合 groupby 结果?

    python - 使用 numpy.genfromtxt 读取包含逗号的字符串的 csv 文件

    python pyplot 产生具有不同虚线参数的线型循环

    python - 在 matplotlib 中查看然后自动关闭图形?

    matplotlib - 如何在单个 IPython 笔记本中多次显示相同的 matplotlib 图?

    python - cx_Freeze 以包含依赖的 py 文件

    php - 使 RSA 加密在 Python (PyCrypto) 和 PHP (OpenSSL) 中兼容

    python - 在多维数组上使用 numpy.argmax()

    python - 如何对数组中的范围值求和,其中每行都有不同的范围