如何將此堆疊條更改為 帶有百分比標簽的堆疊百分比條圖:
這是代碼:
df_responses= pd.read_csv('https://raw.githubusercontent.com/eng-aomar/Security_in_practice/main/secuirtyInPractice.csv')
df_new =df_responses.iloc[:,9:21]
image_format = 'svg' # e.g .png, .svg, etc.
# initialize empty dataframe
df2 = pd.DataFrame()
# group by each column counting the size of each category values
for col in df_new:
grped = df_new.groupby(col).size()
grped = grped.rename(grped.index.name)
df2 = df2.merge(grped.to_frame(), how='outer', left_index=True, right_index=True)
# plot the merged dataframe
df2.plot.bar(stacked=True)
plt.show()
uj5u.com熱心網友回復:
您可以自己計算百分比,例如在資料框的新列中,因為您確實有絕對值并繪制此列。使用sum()和劃分使用資料框你應該很快到達那里。
你可能想看看GeeksForGeeks 的帖子,它展示了如何做到這一點。
編輯
我現在已經繼續并調整了你的程式,所以它會給出你想要的結果(至少是我認為你想要的結果)。我使用而您沒有使用的兩個關鍵功能是df.value_counts()和df.transpose()。您可能想閱讀這兩個,因為它們在許多情況下都非常有用。
import pandas as pd
import matplotlib.pyplot as plt
df_responses= pd.read_csv('https://raw.githubusercontent.com/eng-aomar/Security_in_practice/main/secuirtyInPractice.csv')
df_new =df_responses.iloc[:,9:21]
image_format = 'svg' # e.g .png, .svg, etc.
# initialize empty dataframe providing the columns
df2 = pd.DataFrame(columns=df_new.columns)
# loop over all columns
for col in df_new.columns:
# counting occurences for each value can be done by value_counts()
val_counts = df_new[col].value_counts()
# replace nan values with 0
val_counts.fillna(0)
# calculate the sum of all categories
total = val_counts.sum()
# use value count for each category and divide it by the total count of all categories
# and multiply by 100 to get nice percent values
df2[col] = val_counts / total * 100
# columns and rows need to be transposed in order to get the result we want
df2.transpose().plot.bar(stacked=True)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440758.html
標籤:熊猫 matplotlib 堆积图
