【问题标题】:Connect different data series with the same line用同一条线连接不同的数据系列
【发布时间】:2015-02-28 00:42:06
【问题描述】:

有没有办法让 matplotlib 用同一行连接来自两个不同数据集的数据?

上下文:我需要以对数比例绘制一些数据,但其中一些是负数。我使用以不同颜色(红色为正,绿色为负)绘制数据绝对值的解决方法,例如:

import pylab as pl
pl.plot( x, positive_ys, 'r-' )        # positive y's
pl.plot( x, abs( negative_ys ), 'g-' ) # negative y's
pl.show()

但是,由于它们代表相同的数量,因此将两个数据系列通过同一条线连接会很有帮助。这可能吗?

我不能使用pl.plot( x, abs( ys )),因为我需要能够区分正值和最初的负值。

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    使用 numpy,您可以使用逻辑索引。

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    x = np.array([10000, 1000, 100, 10, 1, 5, 50, 500, 5000, 50000])
    y = np.array([-10000, -1000, -100, -10, -1, 5, 50, 500, 5000, 50000])
    
    ax.plot(x,abs(y),'+-b',label='all data')
    ax.plot(abs(x[y<= 0]),abs(y[y<= 0]),'o',markerfacecolor='none', 
                                            markeredgecolor='r', 
                                            label='we are negative')
    
    ax.set_xscale('log')
    ax.set_yscale('log')
    
    ax.legend(loc=0)
    
    plt.show()
    

    关键特性是首先绘制所有绝对的y-values,然后将那些原本为负的值重新绘制为空心圆圈以将它们单独列出。第二步使用逻辑索引x[y&lt;=0]y[y&lt;=0] 仅选择y-array 中那些为负的元素。

    上面的例子给你这个图:


    如果你真的有两个不同的数据集,下面的代码会给你和上面一样的图:

    x1 = np.array([1, 10, 100, 1000, 10000])
    x2 = np.array([5, 50, 500, 5000, 50000])
    
    y1 = np.array([-1, -10, -100, -1000, -10000])
    y2 = np.array([5, 50, 500, 5000, 50000])
    
    x = np.concatenate((x1,x2))
    y = np.concatenate((y1,y2))
    
    sorted = np.argsort(y)
    
    ax.plot(x[sorted],abs(y[sorted]),'+-b',label='all data')
    ax.plot(abs(x[y<= 0]),abs(y[y<= 0]),'o',markerfacecolor='none',
                                            markeredgecolor='r', 
                                            label='we are negative')
    

    在这里,您首先使用np.concatenate 组合x- 和y- 数组。然后,您使用np.argsorty-array 进行排序,以确保您在绘图时不会得到过于曲折的线。当您调用第一个图时,您使用该索引数组 (sorted)。由于第二个图只绘制符号而不绘制连接线,因此此处不需要排序数组。

    【讨论】:

    • 非常感谢!这就是我要找的东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多