【问题标题】:Plotting an array of events with respective colours绘制具有各自颜色的事件数组
【发布时间】:2019-09-22 18:14:56
【问题描述】:

我对 matplotlib 很陌生,我正在尝试绘制一个数组以供时间序列使用,但我不使用日期,只使用顺序索引。我有另一个数组,前一个数组中的每个条目都有一个颜色代码。

我正在尝试将它们与this 类似,但仅在一行中。

我的数据如下:

array = ['event0', 'event1', 'event2', 'event0', 'event6', ..]
colours = ['r', 'g', 'b', 'r', 'y', ..]

【问题讨论】:

  • 您向我们展示的数据以及您在@shivammittal99 答案下的评论让我感到不安,您到底在绘制什么?时间戳?字符串列表?还有什么?
  • 您如何想象要显示重复项?

标签: python numpy matplotlib plot time-series


【解决方案1】:
import matplotlib.pyplot as plt

# input data
array = ['event0', 'event1', 'event2', 'event0', 'event6']
colours = ['r', 'g', 'b', 'r', 'y']

# for easier plotting, convert your data into numerical data:

方法一:

相同类型的事件获得相同的 y 坐标

array_numbers = [float(a.split('event')[1]) for a in array]

方法二:

所有事件都获得相同的 y 坐标:

array_numbers = [1 for a in array]

绘图:

# create figure, and subplots
fig = plt.figure()
ax = plt.subplot(111)

# plot newly generated numbers against their index, using the colours specified
ax.scatter(range(len(array_numbers)), array_numbers, c=colours)

# create ticklabels:
y_tick_labels = ['sensor-{}'.format(a) for a in range(7)]

# set positions of ticks, and add names
ax.set_yticks(range(7))
ax.set_yticklabels(y_tick_labels)

【讨论】:

    【解决方案2】:

    您可以使用plt.scatter(x, y, c=colours)

    【讨论】:

    • 我已经尝试过了,但它不适用于重复项(例如 event0 出现在 2 个不同的时间)。它只绘制每个事件的第一次出现
    猜你喜欢
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多