Python使用Matpoltlib绘制矩形树图

149 阅读1分钟

引入依赖

import matplotlib.pyplot as plt
import pandas as pd
import squarify

显示中文和负号

# 中文及负号处理
plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'
plt.rcParams['axes.unicode_minus'] = False

数据预处理

data = pd.read_csv('./lipstick_v2.csv', encoding='UTF8')

# 获取广东各城市销售额
guangdongSales = data[data['location'].str.contains('广东')][['location', 'sales']]
# 按城市分类汇总销售额
gaungdongCitySales = guangdongSales.groupby('location')['sales'].sum()
# 广东总销售额
guangdongSalesSum = gaungdongCitySales.values.sum()

labels = []
income = []
area_list = ['广州', '深圳', '汕头', '珠海', '佛山']
for area in area_list:
    labels.append(area)
    income.append(round(gaungdongCitySales[gaungdongCitySales.index.str.contains(area)].sum(), 2))
    guangdongSalesSum = guangdongSalesSum - gaungdongCitySales[gaungdongCitySales.index.str.contains(area)].sum()
labels.append('其他')
income.append(round(guangdongSalesSum, 2))

绘制饼图

fig = plt.figure(figsize=(12, 6))
ax = fig.add_subplot(111)
plot = squarify.plot(sizes=income,  # 方块面积大小
                     label=labels,  # 指定标签
                     # color = colors, # 指定自定义颜色
                     alpha=0.8,  # 指定透明度
                     value=income,  # 添加数值标签
                     edgecolor='white',  # 设置边界框
                     linewidth=0.1  # 设置边框宽度
                     )
# 设置标签大小
plt.rc('font', size=14)  # 无效!
# 设置标题大小
ax.set_title('广东省各地区销售占比+2023120800', fontsize=22)
# 去除坐标轴
ax.axis('off')
# 去除上边框和右边框刻度
ax.tick_params(top='off', right='off')
# 显示图形
plt.show()

效果图

Figure_3.png