import numpy as np
from matplotlib.pyplot import step, show
def binary_data(data):
return [1 if x in data else 0 for x in range(data[-1] + 1)]
data = [1, 2, 4, 5, 9]
bindata = binary_data(data)
xaxis = np.arange(0, data[-1] + 1)
yaxis = np.array(bindata)
step(xaxis, yaxis)
show()
要绘制堆叠在同一图形上的多个数据数组,可以对binary_data()进行如下调整:
def binary_data(data, yshift=0):
return [yshift+1 if x in data else yshift for x in range(data[-1] + 1)]
import numpy as np
from matplotlib.pyplot import step, show
def binary_data(data, limit, yshift=0):
return [yshift+1 if x in data else yshift for x in range(limit)]
data = [ [1, 2, 4, 5, 9, 12, 13, 14],
[1, 4, 10, 11, 20, 21, 22],
[1, 2, 3, 4, 15, 16, 17, 18] ]
# find out the longest data to plot
limit = max( [ x[-1] + 1 for x in data] )
x = np.arange(0, limit)
for shift, d in enumerate(data):
bindata = binary_data(d, limit, 2 * shift)
y = np.array(bindata)
step(x, y)
show()
import numpy as np
from matplotlib.pyplot import step, show
data = [ [1, 2, 4, 5, 9, 12, 13, 14],
[1, 4, 10, 11, 20, 21, 22],
[1, 2, 3, 4, 15, 16, 17, 18] ]
# find out the longest data to plot
limit = max( [ x[-1] + 1 for x in data] )
x = np.arange(0, limit)
for shift, d in enumerate(data):
y = np.zeros_like(x)
y[d] = 1
# don't forget to shift
y += 2*shift
step(x, y)
show()
你明白了。您可以在数据中指定的任何位置使用
1
创建列表,在其他位置使用0
。有了列表理解,这很容易做到会像这样:
现在你所要做的就是策划它。。。或者更好的步骤因为它是二进制数据,
step()
看起来更好:要绘制堆叠在同一图形上的多个数据数组,可以对
binary_data()
进行如下调整:所以现在可以设置
yshift
参数来移动y轴上的数据数组。E、 g假设你有
data1
,data2
和data3
来进行叠加,你会这样:您可以轻松编辑以使其与任意数量的数据数组一起工作:
最后,如果处理的是不同长度的数据数组(比如
[1,2]
和[15,16]
),并且您不喜欢图中间消失的图,则可以再次调整binary_data()
以将其范围强制设置为数据的最大范围。编辑:如@ImportanceOfBeingErnest所建议,如果您希望执行
data
到bindata
的转换,而不必定义自己的binary_data()
函数,则可以使用numpy.zeros_like()
。叠起来的时候要多加注意:可以创建一个全为零的数组,并为数据中的这些元素分配
1
然后可以用step函数绘制
或者使用
where = "pre"
,这取决于如何解释数据相关问题 更多 >
编程相关推荐