如果要更改折线图中以数据段为单位的线颜色,则需要将用于折线图的数据转换为(x1,y1)、(x2,y2)。然后创建一个列表来设置该部分的颜色。对于每个数据,指定绘图功能;x轴上的时间序列将最后更新。也许可以按原样处理时间序列,但我认为更容易将其作为向量处理,然后再将其作为时间序列处理。这是对这个答案的提示。我在修改什么
this answer
是指定最后一个值的方式,因为使用的数据是一个系列。
import pandas as pd
import numpy as np
import io
data = '''
time A price B side size signal
"2019-06-12 03:54:26.668990" 4603.35936 7990.0 4583.96620 Buy 20 True
"2019-06-12 03:54:26.668990" 4603.24884 7990.0 4583.96620 Buy 38 True
"2019-06-12 03:54:26.668990" 4603.26808 7990.0 4583.96620 Buy 69 True
"2019-06-12 03:54:26.668990" 4603.32670 7990.0 4583.96620 Buy 25 True
"2019-06-12 03:54:26.668990" 4603.32670 7990.0 4583.96620 Buy 450 True
"2019-06-12 12:07:48.793863" 3997.85136 8043.5 4375.44562 Buy 22 False
"2019-06-12 12:07:48.793863" 3997.87648 8044.0 4375.44562 Buy 1300 False
"2019-06-12 12:07:48.793863" 3997.87616 8044.0 4375.44562 Buy 6 False
"2019-06-12 12:07:48.793863" 3997.89530 8044.0 4375.44562 Buy 1000 False
"2019-06-12 12:07:48.793863" 3997.90046 8044.0 4375.44562 Buy 280 False
'''
df = pd.read_csv(io.StringIO(data), delim_whitespace=True)
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig, ax = plt.subplots()
y = df['price']
x = np.arange(len(y))
# x:numpy.array, y:pandas.Series
segments_x = np.r_[x[0], x[1:-1].repeat(2), x[-1]].reshape(-1, 2)
segments_y = np.r_[y[0], y[1:-1].repeat(2), y[:-1]].reshape(-1, 2)
# print(segments_x, segments_y, sep='\n')
colors = ['green' if x == True else 'red' for x in df['signal']]
segments = [[x_, y_] for x_, y_ in zip(segments_x, segments_y)]
# print(segments)
for s,c in zip(segments, colors):
ax.plot(s[0],s[1],color=c)
ax.set_xticks(x)
ax.set_xticklabels(df['time'].tolist(), rotation=90)
plt.show()