【问题标题】:Creating color-coded horizontal bars in matplotlib在 matplotlib 中创建颜色编码的水平条
【发布时间】:2022-01-16 14:05:41
【问题描述】:

我正在开发一种 QC 工具,以根据多个标准“标记”来自时间序列的可疑数据。好的数据将被标记为 1,坏数据被标记为 0。我想将包含 0 和 1 值的结果数组显示为颜色编码的水平条。

让我们考虑以下虚拟数组myarray

import numpy as np
import matplotlib.pyplot as plt
mysamples=np.arange(3600)
myarray = np.ones(3600)
myarray[300:500]=0
myarray[1300:1800]=0

我想出了以下解决方案来显示它:

使用bar的解决方案

fig, axs = plt.subplots(2, gridspec_kw={'height_ratios': [5, 1]})
fig.suptitle('QC flag example 1')
axs[0].plot(mysamples,myarray)
axs[1].bar(mysamples[myarray==1], height=1, linewidth=0, color='green')
axs[1].bar(mysamples[myarray==0], height=1, linewidth=0, color='red')

使用scatter的解决方案

fig, axs = plt.subplots(2, gridspec_kw={'height_ratios': [5, 1]})
fig.suptitle('QC flag example 2')
axs[0].plot(mysamples,myarray)
axs[1].scatter(mysamples[myarray==1],mysamples[myarray==1]*0 , marker='s', color='green')
axs[1].scatter(mysamples[myarray==0], mysamples[myarray==0]*0, marker='s', color='red')

我更喜欢选项 2,因为它可以让我在彼此之上绘制多个 QC 轨迹,但我仍然认为这是显示 myarray 的一种复杂方式。例如,如果标记大小处理不当,最终可能会生成不连续的条形图。

还有其他 matplotlib 函数可以创建这样的水平条吗?

注意:我知道plotly 有很多选项,例如甘特图,但目前我更愿意坚持使用 matplotlib。

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    我不确定这有多简单,但我使用水平条形图来处理它。创建一个相同长度的array1,并使用原始数组进行颜色确定。然后将其以索引为左侧位置堆叠在一个循环过程中。

    fig, axs = plt.subplots(2, gridspec_kw={'height_ratios': [5, 1]})
    fig.suptitle('QC flag example 1')
    
    axs[0].plot(mysamples,myarray)
    # axs[1].bar(mysamples[myarray==1], height=1, linewidth=0, color='green')
    # axs[1].bar(mysamples[myarray==0], height=1, linewidth=0, color='red')
    new_array = [1]*len(myarray)
    colors = [('g' if i == 1 else 'r') for i in myarray]
    for i,a in enumerate(new_array):
        axs[1].barh(y=0, width=a, height=0.5, left=i, color=colors[i])
    x0,x1 = axs[0].get_xlim()
    axs[1].set_xlim(x0, x1)
    
    plt.show()
    

    【讨论】:

    • 非常感谢您的回答。它可能并不比我建议的更简单,但我认为它会更加健壮。
    • 条件颜色编码恰到好处!
    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 2019-04-21
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2018-09-09
    • 2013-04-02
    • 1970-01-01
    相关资源
    最近更新 更多