用数据库保存某公司在郑州和洛阳两地2021和2022年的5种不同品牌手机的累计销售额,利用pyecharts选择合适可视化图进行展示,要求能够利用工具框切换为其他不同类型图表,画布上方居中有本人学号姓名等信息。
时间: 2023-06-15 16:07:41 浏览: 66
以下是一个利用pyecharts进行可视化展示的示例代码:
```python
from pyecharts import options as opts
from pyecharts.charts import Bar, Line, Grid, Tab
from pyecharts.faker import Faker
import pymysql
# 连接数据库
connection = pymysql.connect(host='localhost',
user='root',
password='123456',
db='sales',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
# 查询数据
try:
with connection.cursor() as cursor:
sql = "SELECT * FROM sales"
cursor.execute(sql)
results = cursor.fetchall()
finally:
connection.close()
# 处理数据
data = {}
for result in results:
city = result['city']
year = result['year']
brand = result['brand']
sales = result['sales']
if city not in data:
data[city] = {}
if year not in data[city]:
data[city][year] = {}
data[city][year][brand] = sales
# 生成图表
tab = Tab()
for city in data:
years = sorted(list(data[city].keys()))
brands = sorted(list(data[city][years[0]].keys()))
# 生成柱状图
bar = Bar()
bar.add_xaxis(years)
for brand in brands:
sales = [data[city][year][brand] for year in years]
bar.add_yaxis(brand, sales)
bar.set_global_opts(title_opts=opts.TitleOpts(title=f'{city}手机销售额'),
toolbox_opts=opts.ToolboxOpts())
tab.add(bar, city)
# 生成折线图
line = Line()
line.add_xaxis(years)
for brand in brands:
sales = [data[city][year][brand] for year in years]
line.add_yaxis(brand, sales, is_smooth=True)
line.set_global_opts(title_opts=opts.TitleOpts(title=f'{city}手机销售额'),
toolbox_opts=opts.ToolboxOpts())
tab.add(line, city)
# 生成网格图
grid = Grid()
grid.add(tab, grid_opts=opts.GridOpts())
grid.set_global_opts(title_opts=opts.TitleOpts(title='手机销售额'),
toolbox_opts=opts.ToolboxOpts())
grid.render_notebook()
```
其中,需要先连接数据库,查询数据,然后处理数据,最后生成图表。此示例中采用了Tab和Grid两种容器来进行不同类型图表的切换。具体实现方式可以参考pyecharts官方文档。
在画布上方居中显示本人学号姓名等信息可以在生成图表时通过`title_opts`参数来设置。例如:
```python
bar.set_global_opts(title_opts=opts.TitleOpts(title='手机销售额', subtitle='学号:123456,姓名:张三'))
```
这样就可以在图表上方居中显示学号、姓名等信息了。
阅读全文