有没有办法让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 ))
因为我需要能够区分正值和原始负值。
通过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
-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.argsort
某种方式对y
-array进行排序,以确保在绘制时不会出现过大的锯齿形线条。sorted
调用第一个图时,将使用该索引数组()。由于第二个图仅绘制符号而没有连接线,因此此处不需要排序数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句