Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Matplotlib直方图,其中每个箱子由附加参数的频率着色_Python_Matplotlib - Fatal编程技术网

Python Matplotlib直方图,其中每个箱子由附加参数的频率着色

Python Matplotlib直方图,其中每个箱子由附加参数的频率着色,python,matplotlib,Python,Matplotlib,如果我有 data = [(1, 'a'), (1, 'b'), (1, 'a'), (2, 'a'), (2, 'b'), (3, 'c'), (3, 'c'), (3, 'c'), (3, 'c')] 这样,每个数据点有两个属性: x, y = zip(*data) 我可以在直方图中显示x,ala: x = [1, 1, 1, 2, 2, 3, 3, 3, 3] bins = [1, 2, 3]; f = [3, 2, 4]`. 然后,使用第二个属性 y = ['a', 'b',

如果我有

data = [(1, 'a'), (1, 'b'), (1, 'a'), (2, 'a'), (2, 'b'), (3, 'c'), (3, 'c'), (3, 'c'), (3, 'c')] 
这样,每个数据点有两个属性:

x, y = zip(*data)
我可以在直方图中显示x,ala:

x = [1, 1, 1, 2, 2, 3, 3, 3, 3]
bins = [1, 2, 3]; f = [3, 2, 4]`. 
然后,使用第二个属性

y = ['a', 'b', 'a', 'a', 'b', 'c', 'c', 'c', 'c']
原始直方图中的每个箱子都有次要参数的频率信息:

bins[0] = {'a': 2, 'b': 1}
bins[1] = {'a': 1, 'b': 1}
bins[2] = {'b': 1, 'c': 3}
使用matplotlib,我可以创建x的基本直方图:

有没有一种聪明的方法可以迭代这些面片,或者将它们分解成大小合适的矩形,以反映附加信息y

在这个例子中,如果我希望“a”是红色,“b”是绿色,“c”是蓝色,那么第一个箱子x=1将是三分之二的红色和三分之一的绿色,第二个箱子x=2将是半红色和半绿色,最后一个箱子x=3将是四分之一的绿色和四分之三的蓝色


我意识到这不是一个完整的答案,但如果您要重新格式化数据,那么您可以使用hist的一些内置功能,以避免手工编写所有代码

例如,您可以创建一个列表,其中包含所有x值,其中y值等于“a”,另一个列表中y='b',最后一个列表中y='c'。然后,您可以将这些列表堆叠到另一个列表中,并对该数据调用hist,stacked=True

请参见下面的第五个面板以获取图示。

是否提供帮助?
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 3)