如何根据时间戳上的单元格值绘制颜色
How to plot colors based on cell values on a timestamp
我有一个包含 16 列的数据,其中 1 列是“时间”列,其他 15 列是代表颜色的列。数据如下所示:
我需要的是在每个时间戳代表这 15 种颜色的绘图。
输出应如下所示:
知道怎么做吗?
谢谢!!
而不是使用 bar
,在这些情况下通常更方便的是在段中使用正常的 plot
。这是一个玩具示例。
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'Time':[0.3, 1.5, 1.8, 4.7, 5.8],
'SG1':['red', 'green', 'grey', 'yellow', 'red'],
'SG2':['grey', 'red', 'grey', 'yellow', 'grey'],
'SG3':['red', 'red', 'grey', 'yellow', 'red'],
'SG4':['red', 'green', 'grey', 'green', 'red']})
Time SG1 SG2 SG3 SG4
0 1 red grey red red
1 2 green grey red green
2 3 grey grey grey green
3 4 yellow yellow yellow green
4 5 red grey red red
代码:
LINE_THICKNESS = 10
FIG_SIZE = (4, 3) # Size (width, height).
f, ax = plt.subplots(figsize=FIG_SIZE)
groups = sorted([c for c in df.columns if 'SG' in c])
for i, group in enumerate(groups):
colors = df[group]
for (color, t0), t1 in zip(zip(colors, df['Time']), df['Time'][1:]):
ax.plot([t0, t1], [i, i], color=color, linewidth=LINE_THICKNESS)
plt.xlabel('Time')
plt.ylim([-0.5, len(groups)-0.5])
plt.yticks(range(len(groups)), groups)
plt.ylabel('Groups')
plt.title("Signal plan 2", weight='bold')
plt.tight_layout()
plt.show()
给出:
您可以使用 LINE_THICKNESS
和 FIG_SIZE
作为维度。
编辑:
zip
built-in function 获取可迭代对象并将它们聚合在一个元组中。所以:
zip(colors, df['Time'])
获取 (color, time_start) 元组,将时间点与颜色相关联。我们在下一行中称其为 time_colors
。
zip(time_colors, df['Time'][1:])
同样将 (color, time_start) 元组与下一个时间点相关联。这需要知道停止画线的限制。
我有一个包含 16 列的数据,其中 1 列是“时间”列,其他 15 列是代表颜色的列。数据如下所示:
我需要的是在每个时间戳代表这 15 种颜色的绘图。
输出应如下所示:
知道怎么做吗?
谢谢!!
而不是使用 bar
,在这些情况下通常更方便的是在段中使用正常的 plot
。这是一个玩具示例。
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'Time':[0.3, 1.5, 1.8, 4.7, 5.8],
'SG1':['red', 'green', 'grey', 'yellow', 'red'],
'SG2':['grey', 'red', 'grey', 'yellow', 'grey'],
'SG3':['red', 'red', 'grey', 'yellow', 'red'],
'SG4':['red', 'green', 'grey', 'green', 'red']})
Time SG1 SG2 SG3 SG4
0 1 red grey red red
1 2 green grey red green
2 3 grey grey grey green
3 4 yellow yellow yellow green
4 5 red grey red red
代码:
LINE_THICKNESS = 10
FIG_SIZE = (4, 3) # Size (width, height).
f, ax = plt.subplots(figsize=FIG_SIZE)
groups = sorted([c for c in df.columns if 'SG' in c])
for i, group in enumerate(groups):
colors = df[group]
for (color, t0), t1 in zip(zip(colors, df['Time']), df['Time'][1:]):
ax.plot([t0, t1], [i, i], color=color, linewidth=LINE_THICKNESS)
plt.xlabel('Time')
plt.ylim([-0.5, len(groups)-0.5])
plt.yticks(range(len(groups)), groups)
plt.ylabel('Groups')
plt.title("Signal plan 2", weight='bold')
plt.tight_layout()
plt.show()
给出:
您可以使用 LINE_THICKNESS
和 FIG_SIZE
作为维度。
编辑:
zip
built-in function 获取可迭代对象并将它们聚合在一个元组中。所以:
zip(colors, df['Time'])
获取 (color, time_start) 元组,将时间点与颜色相关联。我们在下一行中称其为time_colors
。zip(time_colors, df['Time'][1:])
同样将 (color, time_start) 元组与下一个时间点相关联。这需要知道停止画线的限制。