离散值的堆积直方图

时间:2016-10-15 13:54:40

标签: python-2.7 matplotlib plot

有一些像

这样的数据

OrderedDict([(734242, [1, 0, 1]), (734243, [0, 0, 1]), (734244, [0, 0, 0]), (734245, [3, 0, 1]), (734246, [0, 0, 0]), (734247, [0, 0, 0]), (734248, [0, 0, 0]), (734249, [0, 0, 0]), (734250, [0, 0, 0]), (734251, [0, 0, 0]), (734252, [0, 0, 0]), (734253, [0, 0, 0]), (734254, [0, 0, 0]), (734255, [0, 0, 0]), (734256, [0, 0, 0]), (734257, [0, 0, 0]), (734258, [0, 0, 0]), (734259, [1, 0, 0]), (734260, [0, 0, 0]), (734261, [0, 0, 0]), (734262, [0, 0, 0]), (734263, [0, 0, 0]), (734264, [0, 0, 0]), (734265, [0, 0, 0]), (734266, [0, 0, 0]), (734267, [0, 0, 0]), (734268, [0, 0, 0]), (734269, [0, 0, 0]), (734270, [0, 0, 0]), (734271, [0, 0, 0]), (734272, [0, 0, 0]), (734273, [0, 0, 0]), (734274, [0, 0, 0]), (734275, [0, 0, 0]), (734276, [0, 0, 0]), (734277, [0, 0, 0]), (734278, [0, 0, 0]), (734279, [0, 0, 0]), (734280, [0, 0, 0]), (734281, [0, 0, 0]), (734282, [0, 0, 0]), (734283, [0, 0, 0]), (734284, [0, 0, 0]), (734285, [0, 0, 0]), (734286, [0, 0, 0]), (734287, [0, 0, 0]), (734288, [1, 0, 0])]) (已经是类似堆叠的直方图),

如何创建类似于此

的堆叠直方图

enter image description here

但是,从OrderedDict的键中获取x轴上的值,以及在该键处找到的值作为各个堆叠段的高度?

例如,(734245, [3, 0, 1])应使matplotlib在x坐标734245处显示高度为3的条,然后在其顶部显示高度为0(不可见)的段,以及高度为1的另一段它,使最终的杆4高。

输入数据可能变大,大约10k x坐标,因此性能很重要。

欢迎使用任何图书馆,matplotlib不是强制性的。

1 个答案:

答案 0 :(得分:0)

这是一种效率很低的方法,但它可以帮助你开始。

a = dict([(734242, [1, 0, 1]), (734243, [0, 0, 1]), (734244, [0, 0,
0]), (734245, [3, 0, 1]), (734246, [0, 0, 0]), (734247, [0, 0, 0]),
(734248, [0, 0, 0]), (734249, [0, 0, 0]), (734250, [0, 0, 0]), (734251,
[0, 0, 0]), (734252, [0, 0, 0]), (734253, [0, 0, 0]), (734254, [0, 0,
0]), (734255, [0, 0, 0]), (734256, [0, 0, 0]), (734257, [0, 0, 0]),
(734258, [0, 0, 0]), (734259, [1, 0, 0]), (734260, [0, 0, 0]), (734261,
[0, 0, 0]), (734262, [0, 0, 0]), (734263, [0, 0, 0]), (734264, [0, 0,
0]), (734265, [0, 0, 0]), (734266, [0, 0, 0]), (734267, [0, 0, 0]),
(734268, [0, 0, 0]), (734269, [0, 0, 0]), (734270, [0, 0, 0]), (734271,
[0, 0, 0]), (734272, [0, 0, 0]), (734273, [0, 0, 0]), (734274, [0, 0,
0]), (734275, [0, 0, 0]), (734276, [0, 0, 0]), (734277, [0, 0, 0]),
(734278, [0, 0, 0]), (734279, [0, 0, 0]), (734280, [0, 0, 0]), (734281,
[0, 0, 0]), (734282, [0, 0, 0]), (734283, [0, 0, 0]), (734284, [0, 0,
0]), (734285, [0, 0, 0]), (734286, [0, 0, 0]), (734287, [0, 0, 0]),
(734288, [1, 0, 0])])


for b in a:
    plt.bar(x=b, height=a[b][0], color='r')
    plt.bar(x=b, height=a[b][1], bottom=a[b][0], color='b')
    plt.bar(x=b, height=a[b][2], bottom=a[b][1], color='g')

enter image description here

为了提高效率,您必须将字典转换为数组。所有参数x=height=bottom=都可以将数组作为参数。然后,您可以将代码缩减为3 plt.bar()次来电。