实验:PyEcharts 旭日图
目的:了解并掌握 PyEcharts 库来制作旭日图
原理:Pyecharts是一个用于生成Echarts 图表的类库,可以与Python进行对接,方便在 Python中直接
生成图形。Echarts是百度开源的一个数据可视化JS库,它实现的可视化效果非常美观,凭借着良好的交互
性、精巧的图表设计,得到了众多开发者的认可。
要求:
使用数据库中的订单表(orders)中的数据,绘制如下所示的不同分类下的商品销售额旭日图。
代码:
方法1;
from sqlalchemy import create_engine
import pandas as pdfrom pyecharts import options as optsfrom pyecharts.charts import Sunburstengine = create_engine('mysql+pymysql://root:root@localhost:3306/sales')
sql = '''SELECT DISTINCT category FROM orders'''df = pd.read_sql(sql, engine)data = []
for c in df['category']:sql = '''SELECT subcategory AS 'sc',ROUND(SUM(sales) / 10000, 2) AS 's'FROM ordersWHERE category = '{}'GROUP BY subcategory'''.format(c)subdf = pd.read_sql(sql, engine)cs = [opts.SunburstItem(name=row['sc'], value=row['s']) for (i, row) in
subdf.iterrows()]data.append(opts.SunburstItem(name=c, children=cs))(Sunburst().add(series_name="商品销售额", data_pair=data, radius=[0, "85%"]).set_global_opts(title_opts=opts.TitleOpts(title="不同分类下的商品销售额旭日图"),toolbox_opts=opts.ToolboxOpts()).set_series_opts(label_opts=opts.LabelOpts(formatter="{b}"))
).render('旭日图.html')
方法2:
from sqlalchemy import create_engine
import pandas as pdfrom pyecharts import options as opts
from pyecharts.charts import Sunburstengine = create_engine('mysql+pymysql://root:root@localhost:3306/sales')
sql = '''
SELECT
category AS 'c',
subcategory AS 'sc',
ROUND(SUM(sales) / 10000, 2) AS 's'
FROM orders
GROUP BY category, subcategory
'''df = pd.read_sql(sql, engine)dt = {}for (i, row) in df.iterrows():c = row['c']v = opts.SunburstItem(name=row['sc'], value=row['s'])if c in dt:dt[c]['children'].append(v)else:dt[c] = {'name': c,'children': [v]}data = [opts.SunburstItem(name=c, children=v['children']) for (k, v) in
dt.items()](Sunburst().add(series_name="商品销售额", data_pair=data, radius=[0, "85%"]).set_global_opts(title_opts=opts.TitleOpts(title="不同分类下的商品销售额旭日
图"),toolbox_opts=opts.ToolboxOpts()).set_series_opts(label_opts=opts.LabelOpts(formatter="{b}"))
).render('旭日图.html')