Pandas 在一个地物中创建多个堆叠的条形地块

Pandas 在一个地物中创建多个堆叠的条形地块,pandas,matplotlib,Pandas,Matplotlib,第一个图像是我试图复制的图形,第二个图像是我拥有的数据。有没有人能用pandas或matplotlib实现这一点的干净方法?您可以尝试以下方法: data = {'squad':[0.661669, 0.127516, 0.095005], 'quac':[0.930514, 0.065951, 0.017680], 'quoref': [0.504963, 0.340364, 0.106700]} df = pd.DataFrame(data) bar

第一个图像是我试图复制的图形,第二个图像是我拥有的数据。有没有人能用pandas或matplotlib实现这一点的干净方法?

您可以尝试以下方法:

data = {'squad':[0.661669, 0.127516, 0.095005], 
        'quac':[0.930514, 0.065951, 0.017680], 
        'quoref': [0.504963, 0.340364, 0.106700]} 

df = pd.DataFrame(data)

bars_1 = df.iloc[0]
bars_2 = df.iloc[1]
bars_3 = df.iloc[2]

# Heights of bars_1 + bars_2
bars_1_to_2 = np.add(bars_1, bars_2).tolist()

# The position of the bars on the x-axis
r = [0, 1, 2]

plt.figure(figsize = (7, 7))

plt.bar(r, bars_1, color = 'lightgrey', edgecolor = 'white') 
plt.bar(r, bars_2, bottom = bars_1, color = 'darkgrey', edgecolor = 'white') 
plt.bar(r, bars_3, bottom = bars_1_to_2, color = 'dimgrey', edgecolor = 'white') 

plt.yticks(np.arange(0, 1.1, 0.1))
plt.xticks(ticks = r, labels = df.columns)
plt.ylabel('% of Questions')

plt.show()

仅使用数据帧,并将
堆叠
标志设置为true:

将熊猫作为pd导入
从matplotlib导入pyplot作为plt
df=pd.DataFrame({'squad':[0.6616,0.1245,0.0950],
“quac”:[0.83,0.065,0.0176],
“quoref”:[0.504,0.340364,0.1067]})
#转置
绘图_df=df.T
#密谋
ax=绘图\绘图(种类=条形,堆叠=真,旋转=水平)
ax.图例(bbox_to_anchor=(1.05,1),loc='左上角',borderaxespad=0。)
ax.集合标签(“问题百分比”)
plt.紧_布局()
plt.show()

谢谢,但我的数据令人困惑的是,我想为每列绘制一个堆叠条形图。所以在你的例子中,我希望有一个var_1的条形图和一个var_2的条形图,其中每个条形图中组件的高度是列中值的比例。我已经更新了这个例子。希望它有用:)太好了,这正是我需要的——谢谢!