我正在努力創建value_counts()從資料框中的列派生的堆積條形圖。
假設像下面,其中一個資料幀responder并不重要,但想堆疊計數的[1,2,3,4,5]所有q#列。
responder, q1, q2, q3, q4, q5
------------------------------
r1, 5, 3, 2, 4, 1
r2, 3, 5, 1, 4, 2
r3, 2, 1, 3, 4, 5
r4, 1, 4, 5, 3, 2
r5, 1, 2, 5, 3, 4
r6, 2, 3, 4, 5, 1
r7, 4, 3, 2, 1, 5
看起來像,除了每個條都會被標記,q#并且它將包含 5 個部分用于[1,2,3,4,5]從資料計數:

理想情況下,所有條形都將是“100%”寬,將計數顯示為條形的比例。但保證每一responder行都有一個條目,所以如果可能的話,百分比只是一個獎勵。
任何幫助將不勝感激,對matplotlib解決方案略有偏愛。
uj5u.com熱心網友回復:
您可以使用百分比計算條形的高度,并使用ax = percents.T.plot(kind='barh', stacked=True)wherepercents是具有q1,...q5列和1,...,5索引的 DataFrame獲得堆積條形圖。
>>> percents
q1 q2 q3 q4 q5
1 0.196873 0.199316 0.206644 0.194919 0.202247
2 0.205357 0.188988 0.205357 0.205357 0.194940
3 0.202265 0.217705 0.184766 0.196089 0.199177
4 0.199494 0.199494 0.190886 0.198481 0.211646
5 0.196137 0.195146 0.211491 0.205052 0.192174
然后您可以使用ax.patches為每個條添加標簽。可以從原始計數 DataFrame 生成標簽:counts = df.apply(lambda x: x.value_counts())
>>> counts
q1 q2 q3 q4 q5
1 403 408 423 399 414
2 414 381 414 414 393
3 393 423 359 381 387
4 394 394 377 392 418
5 396 394 427 414 388
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
## create some data similar to yours
np.random.seed(42)
categories = ['q1','q2','q3','q4','q5']
df = pd.DataFrame(np.random.randint(1,6,size=(2000, 5)), columns=categories)
## counts will be used for the labels
counts = df.apply(lambda x: x.value_counts())
## percents will be used to determine the height of each bar
percents = counts.div(counts.sum(axis=1), axis=0)
counts_array = counts.values
nrows, ncols = counts_array.shape
indices = [(i,j) for i in range(0,nrows) for j in range(0,ncols)]
percents_array = percents.values
ax = percents.T.plot(kind='barh', stacked=True)
ax.legend(bbox_to_anchor=(1, 1.01), loc='upper right')
for i, p in enumerate(ax.patches):
ax.annotate(f"({p.get_width():.2f}%)", (p.get_x() p.get_width() - 0.15, p.get_y() - 0.10), xytext=(5, 10), textcoords='offset points')
ax.annotate(str(counts_array[indices[i]]), (p.get_x() p.get_width() - 0.15, p.get_y() 0.10), xytext=(5, 10), textcoords='offset points')
plt.show()

uj5u.com熱心網友回復:
- 條注釋最容易實作
- 移調
df與df = pd.DataFrame(data).set_index('responder').T中,互換指數和列,以產生以下情節。figsize=(12, 10)可能需要調整。

資料幀
df
q1 q2 q3 q4 q5 responder r1 5 3 2 4 1 r2 3 5 1 4 2 r3 2 1 3 4 5 r4 1 4 5 3 2 r5 1 2 5 3 4 r6 2 3 4 5 1 r7 4 3 2 1 5per
q1 q2 q3 q4 q5 responder r1 0.333333 0.200000 0.133333 0.266667 0.066667 r2 0.200000 0.333333 0.066667 0.266667 0.133333 r3 0.133333 0.066667 0.200000 0.266667 0.333333 r4 0.066667 0.266667 0.333333 0.200000 0.133333 r5 0.066667 0.133333 0.333333 0.200000 0.266667 r6 0.133333 0.200000 0.266667 0.333333 0.066667 r7 0.266667 0.200000 0.133333 0.066667 0.333333參考
- 如何將圖例從圖中洗掉顯示了格式化和移動圖例的各種方法。
- 在 matplotlib 條形圖上添加值標簽提供了
.bar_label. - 如何向條形圖添加多個注釋
- matplotlib 中的堆疊條形圖并為每個部分添加標簽
- 如何按色調/圖例組用百分比注釋條形圖
- 如何在seaborn的條形頂部添加百分比
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/397676.html標籤:Python 熊猫 matplotlib 注释 堆积图
下一篇:熊貓cumsum并重新開始
- 移調
