下面是一个示例代码,用于按照性别和数值重新排序百分比堆叠柱状图:
import pandas as pd
import matplotlib.pyplot as plt
# 创建示例数据
data = {
'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Female'],
'Value': [20, 30, 40, 50, 60, 70]
}
df = pd.DataFrame(data)
# 按照性别和数值进行分组,并计算每个组的百分比
df['Percentage'] = df.groupby('Gender')['Value'].apply(lambda x: x / x.sum() * 100)
# 按照性别和数值进行排序
df = df.sort_values(['Gender', 'Value'])
# 绘制堆叠柱状图
plt.bar(df.index, df['Percentage'], color=df['Gender'].map({'Male': 'blue', 'Female': 'pink'}))
plt.xticks(df.index, df['Value'])
plt.xlabel('Value')
plt.ylabel('Percentage')
plt.title('Stacked Bar Chart with Gender and Value')
plt.legend(['Male', 'Female'])
plt.show()
这段代码首先创建了一个包含性别和数值的DataFrame。然后,通过groupby
方法按照性别进行分组,并计算每个组的百分比。接下来,使用sort_values
方法按照性别和数值对DataFrame进行排序。
最后,使用plt.bar
函数绘制堆叠柱状图。颜色可以根据性别来区分,然后使用plt.xticks
函数设置x轴刻度,plt.xlabel
和plt.ylabel
设置x轴和y轴标签,plt.title
设置图表标题,plt.legend
设置图例,最后使用plt.show
显示图表。