pandas 如何从宽数据框创建轴上有列名的堆叠条形图

dojqjjoe  于 2023-05-27  发布在  其他
关注(0)|答案(2)|浏览(109)

第一个图像是我试图复制的图形,第二个图像是我拥有的数据。有没有人有一个干净的方法来用pandas或matplotlib做这件事?

clj7thdc

clj7thdc1#

只需转置DataFrame并使用df.plot,并将stacked标志设置为true:

import pandas as pd
from matplotlib import pyplot as 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]})

# Transpose
plot_df = df.T
# plot
ax = plot_df.plot(kind='bar', stacked=True, rot='horizontal')

ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
ax.set_ylabel("% of Questions")

plt.tight_layout()
plt.show()

lymnna71

lymnna712#

你可以试试这个:

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()

相关问题