使用pyecharts库根据字段:‘销售月份', '大类名称’,'销售金额。按月绘制各大类商品销售金额的百分占比饼图,形成按月轮播图
时间: 2023-12-29 19:06:37 浏览: 29
好的,我明白了。首先需要安装pyecharts库。可以使用以下命令安装:
```
pip install pyecharts
```
接下来,我们需要准备数据,数据应该包括销售月份、大类名称、销售金额这三个字段。假设数据已经准备好,并存储在名为data的DataFrame中,可以按以下方式绘制各大类商品销售金额的百分占比饼图:
```python
from pyecharts.charts import Pie
from pyecharts import options as opts
from pyecharts.commons.utils import JsCode
from pyecharts.globals import ThemeType
from datetime import datetime
import pandas as pd
# 准备数据
data = pd.read_csv('data.csv')
# 将销售月份转换为datetime类型
data['销售月份'] = pd.to_datetime(data['销售月份'])
# 获取所有的销售月份
months = sorted(list(set(data['销售月份'])))
# 定义饼图
pie = Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
# 定义轮播图
timeline = (
opts.TimelineOpts()
.add_schema(
axis_type="category",
symbol="circle",
is_auto_play=True,
is_loop_play=True,
play_interval=1000,
width=800,
left="10%",
right="10%",
bottom="5%",
label_opts=opts.LabelOpts(is_show=True, color="#333"),
)
.set_global_opts(
title_opts=opts.TitleOpts(
"各大类商品销售金额的百分占比",
pos_left="50%",
pos_top="5%",
title_textstyle_opts=opts.TextStyleOpts(font_size=30),
),
tooltip_opts=opts.TooltipOpts(
trigger="item",
formatter="{a} <br/>{b}: {c}万元 ({d}%)",
),
legend_opts=opts.LegendOpts(
type_="scroll",
pos_left="20%",
orient="vertical",
item_width=20,
item_height=10,
),
)
)
# 绘制每个月的饼图
for month in months:
# 获取当前月份的数据
month_data = data[data['销售月份'] == month]
# 按大类名称分组并计算销售金额总和
group_data = month_data.groupby('大类名称')['销售金额'].sum()
# 计算总销售金额
total = group_data.sum()
# 将数据转换为列表
data_list = []
for name, value in group_data.items():
data_list.append((name, round(value / total * 100, 2)))
# 绘制饼图
pie.add(
series_name=month.strftime('%Y-%m'),
data_pair=data_list,
radius=["30%", "60%"],
center=["50%", "50%"],
label_opts=opts.LabelOpts(
position="outside",
formatter="{b}: {c}万元 ({d}%)",
font_size=14,
font_weight="bold",
font_family="Microsoft YaHei",
color="#333",
),
)
# 添加轮播图的时间点
timeline.add(pie, month.strftime('%Y-%m'))
# 将轮播图渲染为HTML文件
timeline.render("pie_chart.html")
```
这段代码会生成一个按月轮播的饼图,每个饼图显示各大类商品销售金额的百分占比。可以通过浏览器打开生成的HTML文件查看结果。