没有合并的堆叠条形图问题

问题描述

我很清楚我想绘制什么,但我不确定从哪里开始使用 matplotlib/seaborn。

我有大约 999 行 不等的 0、1 和 2 行。以下是一行的示例:

[1,1,2,1]

我想绘制一个水平图,其中每个数字都映射到某个设定单位长度的颜色。

这看起来像一个堆积的条形图。但我相信 plt.bar 的功能会汇集值,使得只能有三种连续的颜色。但是我需要实现图形,以便在颜色之间可以有任意数量的切换。

enter image description here

解决方法

对于 1000 行,我想如果您使用 imshow 而不是条形图将数据显示为图像会更好。将您的数据(012)放入 999 行和与最长序列一样多的列的数组中,使用 -1 初始化该数组。

示例只有 100 行以提高可读性:

import matplotlib.pyplot as plt
import numpy as np

# generate some sample data
n,m = 10,20
a = np.random.randint(0,3,(n,m))
s = np.random.randint(int(m/2),m,n)
for i in range(n):
    a[i,s[i]:] = -1

# show them as image
cmap = plt.matplotlib.colors.ListedColormap(['w','r','lime','b'])
plt.imshow(a,cmap=cmap)

enter image description here

然后您可以根据需要调整轴刻度和标签。