2015-02-24 33 views
0

有没有办法让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)),因为我需要能够区分正值和负值。

回答

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 - 值,然后重新绘制那些原本否定的,因为空心圆他们挑出。这第二步使用逻辑索引x[y<=0]y[y<=0]来挑选那些为负数的y数组中的那些元素。

上面的例子给你这个数字:

marked negative


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

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.argsort来排序y -array,以确保在绘图时不会出现过多的曲折线。当您调用第一个绘图时,可以使用该索引数组(sorted)。由于第二个绘图仅绘制符号但没有连接线,因此您不需要在此排序数组。

+0

非常感谢!这就是我一直在寻找的! – user2669155 2015-03-01 03:18:16

相关问题