Skip to main content
 首页 » 编程设计

python之使用 matplotlib 在 python 中绘制堆叠直方图

2024年11月01日898°冷暖

我正在尝试有效地绘制一些数据以便将其可视化,但我遇到了一些麻烦。我有两个值(value)观。一个是离散的(0 或 1),称为 label。另一个是介于 0 和 1 之间的任何连续值。我希望创建一个直方图,其中 X 轴上会有许多条,例如每 .25 个数据一个,所以四个条,其中第一个具有值0-0.25,第二个0.25-0.5,第三个0.5-0.75,第四个0.75-1。

然后 y 轴将根据标签是 1 还是 0 分开,所以我们最终得到这样的图:

如果有任何有效、智能的方法来拆分我的数据(而不是仅仅为这些值硬编码四个条)我也会对此感兴趣,尽管这可能需要另一个问题。当我有这次运行的代码时,我会发布它。

我将两个值都存储在 numpy 数组中,如下所示,但我不确定如何绘制这样的图表:

import numpy as np 
import pylab as P 
 
variable_values = trainData.get_vector('variable') #returns one dimensional numpy array of vals 
label_values = trainData.get_vector('label') 
x = alchemy_category_score_values[alchemy_category_score_values != '?'].astype(float) #removing void vals 
y = label_values[alchemy_category_score_values != '?'].astype(float) 
 
fig = plt.figure() 
 
plt.title("Feature breakdown histogram") 
plt.xlabel("Variable") 
plt.xlim(0, 1) 
plt.ylabel("Label") 
plt.ylim(0, 1) 
xvals = np.linspace(0,1,.02) 
 
plt.show() 

matplotlib 教程显示了以下代码来大致实现我想要的,但我无法真正理解它是如何工作的(LINK):

P.figure() 
 
n, bins, patches = P.hist(x, 10, normed=1, histtype='bar', stacked=True) 
 
P.show() 

非常感谢任何帮助。谢谢。

编辑:

我现在收到错误:

AssertionError: incompatible sizes: argument 'height' must be length 5 or scalar 

我打印了两个 numpy 数组,它们长度相等,一个是离散的,另一个是连续的。这是我正在运行的代码:

x = variable_values[variable_values != '?'].astype(float) 
y = label_values[label_values != '?'].astype(float) 
 
print x #printing numpy arrays of equal size, x is continuous, y is discrete. Both of type float now. 
print y 
 
N = 5 
ind = np.arange(N)    # the x locations for the groups 
width = 0.45       # the width of the bars: can also be len(x) sequence 
 
p1 = plt.bar(ind, y,   width, color='r') #error occurs here 
p2 = plt.bar(ind, x, width, color='y', 
             bottom=x) 
 
plt.ylabel('Scores') 
plt.title('Scores by group and gender') 
plt.xticks(ind+width/2., ('G1', 'G2', 'G3', 'G4', 'G5') ) 
plt.yticks(np.arange(0,81,10)) 
plt.legend( (p1[0], p2[0]), ('Men', 'Women') ) 
 
plt.show() 

请您参考如下方法:

我认为this other tutorial来自同一个 Matplotlib 画廊的内容将对您更具启发性......

注意第二个系列的数据在调用中有一个额外的参数:bottom

p1 = plt.bar(ind, menMeans,   width, color='r', yerr=womenStd) 
p2 = plt.bar(ind, womenMeans, width, color='y', 
             bottom=menMeans, yerr=menStd) 

只需将 menMeans 替换为 x 并将 womenMeans 替换为 y。