我认为您可以使用 matplotlib 中损坏的条形图。文档是here。
这是我测试的一个简单版本:
不幸的是,我想不出一种方法来通过权益向量化操作。
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame()
df['qqq'] = [1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,0,0]
df['dia'] = [0,0,1,1,0,1,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1,1,1,1,1]
ones = []
for col in df.columns:
one = df[df[col].diff() != 0][:][col]
one = one[one == 1]
ones.append(one)
hranges = []
for col in df.columns:
diff = df[df[col].diff() != 0]
spread = pd.DataFrame(diff[col].index, columns=[col])
spread = spread.set_value(len(spread), col, len(df[col].index))
spread = spread.diff(periods=-1).fillna(spread[pd.isnull(spread.diff()) == True])*-1
spread = spread.drop(spread.index[-1])
re_index = pd.DataFrame(df[df[col].diff() != 0][:][col].tolist())
re_index = re_index[re_index[0] == 0]
hranges.append(spread.drop(re_index[re_index[0] == 0].index))
hranges[j].columns = ['width']
hranges[j]['hval'] = ones[j].index.tolist()
cols = hranges[j].columns
cols = cols[-1:] | cols [:-1]
hranges[j] = hranges[j][cols]
j += 1
vals = []
for j in range(len(hranges)):
val = [(hranges[j].hval[i], hranges[j].width[i]) for i in hranges[j].index]
vals.append(val)
fig, ax = plt.subplots()
j = 0
for col in df.columns:
ax.broken_barh(vals[j], ((j+1)*10,10))
j += 1
ax.set_yticks([((k+1) * 10) + 5 for k in range(j)])
ax.set_yticklabels(df.columns)
plt.show()
结果如下:
显然,您的示例将具有 x 轴的时间值,但我想您可以弄清楚。