python百分比堆积柱形图
时间: 2024-07-30 12:01:01 浏览: 172
在Python中,你可以使用matplotlib库以及其子库如pandas和seaborn来创建百分比堆积柱状图。这种类型的图表特别适合展示每个类别内部各个部分所占的比例,常常用于数据可视化,比如市场份额分析。
首先,你需要安装必要的库,如果还没有安装,可以使用pip安装:
```bash
pip install matplotlib pandas seaborn
```
然后,你可以按照以下步骤创建百分比堆积柱状图:
```python
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 假设你有一个DataFrame df,其中包含'Category'和'Share'列
df = pd.DataFrame({
'Category': ['A', 'B', 'C', 'D', 'E'],
'Share': [20, 35, 15, 20, 10]
})
# 计算累计比例
df['Cumulative Share'] = df['Share'].cumsum() / df['Share'].sum()
# 使用seaborn的catplot函数创建堆积柱状图
sns.catplot(
x='Category',
y='Cumulative Share',
data=df,
kind='bar',
stacked=True,
palette='Blues_d'
)
# 添加百分比标签
for p in ax.patches:
width = p.get_width()
height = p.get_height()
ax.text(p.get_x() + width * 0.5, height + 0.02, '{:.1%}'.format(height), ha='center')
plt.xlabel('Categories')
plt.ylabel('Percentage')
plt.title('Percentage Stacked Bar Chart')
plt.show()
```
阅读全文
相关推荐















