,可以通过以下步骤实现:
下面是一个示例代码,实现了上述步骤:
import pandas as pd
import matplotlib.pyplot as plt
# 创建包含需要展示的数据的DataFrame对象
data = {
'Category': ['A', 'B', 'C'],
'Value1': [10, 20, 30],
'Value2': [15, 25, 35],
'Value3': [12, 18, 28]
}
df = pd.DataFrame(data)
# 对DataFrame进行堆叠操作
df_stacked = df.set_index('Category').stack().reset_index()
# 计算每个堆叠类别的总计值
df_sum = df_stacked.groupby('Category')[0].sum().reset_index()
df_sum.columns = ['Category', 'Total']
# 将总计值添加到DataFrame中
df_stacked_with_total = pd.concat([df_stacked, df_sum], ignore_index=True)
# 绘制堆叠条形图
fig, ax = plt.subplots()
colors = ['red', 'green', 'blue']
categories = df_stacked_with_total['Category'].unique()
bottom = pd.Series([0] * len(categories))
for i, category in enumerate(categories):
data_subset = df_stacked_with_total[df_stacked_with_total['Category'] == category]
ax.bar(data_subset.index, data_subset[0], bottom=bottom, label=category, color=colors[i])
bottom += data_subset[0]
# 添加显示总计值的标签
for i, row in df_sum.iterrows():
ax.annotate(row['Total'], (i, row['Total']), ha='center', va='bottom')
# 添加显示百分比的文字
for i, row in df_stacked_with_total.iterrows():
percentage = row[0] / df_sum[df_sum['Category'] == row['Category']]['Total'].values[0] * 100
ax.text(row.name, row[0] / 2, f'{percentage:.1f}%', ha='center', va='center')
# 设置图形属性
ax.set_xlabel('Category')
ax.set_ylabel('Value')
ax.set_title('Stacked Bar Chart with Total and Percentage')
# 显示图形
plt.legend()
plt.show()
上述代码中的示例数据为3个类别(A、B、C)和3个数值(Value1、Value2、Value3),可根据实际需求进行修改。绘制的堆叠条形图中,每个条形上方显示了总计值,每个条形内部显示了相对于总计的百分比。
在腾讯云中,相关的产品和产品介绍链接如下:
领取专属 10元无门槛券
手把手带您无忧上云