|
楼主 |
发表于 2024-5-31 08:47:22
|
显示全部楼层
import re
import math
import pymysql # 导入数据库
from bs4 import BeautifulSoup
from pyecharts.options import *
from pyecharts.faker import Faker
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.charts import Bar, Pie, Page, Geo, Timeline, Line3D, Scatter, Line
def bar(): # 柱状图
year = Numberselect(Mysqlconnect("select year from countrygdp;"))
country = Chineseselect(Mysqlconnect("select GDP from countrygdp;"))
GDP = Numberselect(Mysqlconnect("select rate from countrygdp;"))
data_dict = {}
for i in range(len(year)):
try:
data_dict[year[i]].append([country[i], GDP[i]])
except KeyError:
data_dict[year[i]] = []
data_dict[year[i]].append([country[i], GDP[i]])
# 排序年份
sorted_year_list = sorted(data_dict.keys()) # 排序年份
timeline = Timeline({"theme": ThemeType.LIGHT}) # 创建时间线对象
for year in sorted_year_list:
data_dict[year].sort(key=lambda element: element[1], reverse=True)
year_data = data_dict[year][:8] # 取出本年份前八名的国家
x_data = []
y_data = []
for country_gdp in year_data:
x_data.append(country_gdp[0]) # x轴添加国家
y_data.append(country_gdp[1] / 100000000) # y轴添加GDP数据,单位为亿元
bar = Bar() # 构建柱状图
x_data.reverse()
y_data.reverse()
bar.add_xaxis(x_data)
bar.add_yaxis("GDP亿元", y_data, label_opts=LabelOpts(position="right"), color="#FFFFFF")
bar.reversal_axis() # 反转x轴,y轴
bar.set_global_opts(
title_opts=TitleOpts(title=f"{year}年全球GDP前八数据", title_textstyle_opts=opts.TextStyleOpts(
color="#FFFFFF")),
xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color='#FFFFFF')),
yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color='#FFFFFF'))) # 设置每一年的图表标题
timeline.add(bar, str(year)) # 创建时间线对象
c = timeline.add_schema( # 设置时间为自动播放
play_interval=1000, # 时间间隔
is_timeline_show=True, # 是否显示时间
is_loop_play=True, # 是否循环
is_auto_play=True # 是否自动播放
)
return c
def tab(name, color, size): # 标题
c = (Pie().set_global_opts(title_opts=opts.TitleOpts(title=name, pos_left='center', pos_top='center',
title_textstyle_opts=opts.TextStyleOpts(color=color,
font_size=size))))
return c
def line(): # 折线图
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis(
'Lab A',
Faker.values(),
markline_opts=opts.MarkLineOpts(data=[
{'yAxis': 150},
opts.MarkLineItem(type_='min'),
opts.MarkLineItem(type_='max'),
opts.MarkLineItem(type_='average'),
])).add_yaxis(
'Lab B',
Faker.values(),
markline_opts=opts.MarkLineOpts(data=[
opts.MarkLineItem(type_='min'),
opts.MarkLineItem(type_='max'),
opts.MarkLineItem(type_='average'),
])).set_global_opts(
title_opts=opts.TitleOpts(title='折线图中设置标记', title_textstyle_opts=opts.TextStyleOpts(
color="#FFFFFF")),
xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color='#FFFFFF')),
yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color='#FFFFFF')),
visualmap_opts=opts.VisualMapOpts(
pos_top='10',
pos_right='0',
is_piecewise=True,
pieces=[
{'gt': 0, 'lte': 50, 'color': '#096'},
{'gt': 50, 'lte': 100, 'color': '#ffde33'},
{'gt': 100, 'lte': 150, 'color': '#ff9933'},
{'gt': 150, 'lte': 200, 'color': '#cc0033'},
{'gt': 200, 'lte': 300, 'color': '#660099'},
{'gt': 300, 'color': '#7e0023'}
],
out_of_range={'color': '#999'}
),
datazoom_opts=[
opts.DataZoomOpts(yaxis_index=0),
opts.DataZoomOpts(type_='inside', yaxis_index=0),
]
)
)
return c
def scatter(): # 散点图
# 例1 自定义数据基本示例
y1 = [[12, 4], [2, 5], [2, 6], [3, 15], [3, 6]]
y2 = [[8, 2], [28, 4], [18, 6], [8, 61], [7, 2]]
c = (
Scatter()
.add_xaxis(Faker.choose())
.add_yaxis('数据1', y1)
.add_yaxis('数据2', y2)
.set_global_opts(
title_opts=opts.TitleOpts(title='散点图', title_textstyle_opts=opts.TextStyleOpts(color="#FFFFFF")),
xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color='#FFFFFF')),
yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color='#FFFFFF'))
)
)
return c
def Mysqlconnect(sql): # 数据库连接
conn = pymysql.connect(
host='localhost', # 连接名称,一般默认localhost
user='root', # 数据库用户名,一般都是root
password='123456', # 数据库密码,用户根据自定义设置
port=3306, # MySQL端口,系统默认的3306端口
db='python', # 连接数据库名
charset='utf8'
) # 识别的字符编码
cur = conn.cursor() # 生成游标对象
cur.execute(sql)
sql1 = cur.fetchall() # 通过fetchall获得数据
cur.close()
conn.close()
return sql1
def Chineseselect(datas): # 汉字数据筛选
data = []
for i in datas[:len(datas)]:
data.append(re.search("[\u4e00-\u9fff]+", str(i)).group())
return data
def Numberselect(datas): # 数值数据筛选
data = []
for i in datas[:len(datas)]:
data.append(int(re.search(r"[0-9]+", str(i)).group()))
return data
def radius(): # 饼图
cate = Chineseselect(Mysqlconnect("select area from vote_result"))
data = Numberselect(Mysqlconnect("select vote from vote_result"))
c = Pie()
c.add('', [list(z) for z in zip(cate, data)], radius=["30%", "70%"], rosetype="radius")
c.set_global_opts(title_opts=opts.TitleOpts(title="客户销售额占比", padding=[1, 350],
title_textstyle_opts=opts.TextStyleOpts(color="#FFFFFF")),
legend_opts=opts.LegendOpts(textstyle_opts=opts.TextStyleOpts(color="#FFFFFF"), type_="scroll",
orient="vertical", pos_right=0, pos_top="middle"))
c.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
c.set_colors(['red', "orange", "yellow", "green", "Cyan", "purple"])
return c
def geo(): # 中国地图
city_num = [('武汉', 200), ('成都', 70), ('北京', 99),
('西安', 80), ('杭州', 60), ('贵阳', 34),
('上海', 65), ('深圳', 54), ('乌鲁木齐', 76),
('哈尔滨', 47), ('兰州', 56), ('信阳', 85)]
start_end = [('宁波', '成都'), ('武汉', '北京'), ('武汉', '西安'),
('长沙', '杭州'), ('武汉', '贵阳'), ('武汉', '上海'),
('甘肃', '深圳'), ('北京', '乌鲁木齐'), ('上海', '哈尔滨'),
('武汉', '兰州'), ('西藏', '信阳')]
c = Geo()
c.add_schema(maptype='china', itemstyle_opts=opts.ItemStyleOpts(color='#323c48', border_color='white'))
c.add('', data_pair=city_num, color='white') # 4.添加数据
c.add('', data_pair=start_end, type_="lines", label_opts=opts.LabelOpts(is_show=False),
effect_opts=opts.EffectOpts(symbol="arrow", color='gold', symbol_size=7))
c.set_global_opts(title_opts=opts.TitleOpts(title=""))
return c
def scatter3D(): # 弹簧图
data = []
for t in range(0, 25000):
_t = t / 1000
x = (1 + 0.25 * math.cos(75 * _t)) * math.cos(_t)
y = (1 + 0.25 * math.cos(75 * _t)) * math.sin(_t)
z = _t + 2.0 * math.sin(75 * _t)
data.append([x, y, z])
c = (
Line3D()
.add("", data,
xaxis3d_opts=opts.Axis3DOpts(Faker.clock, type_='value', axislabel_opts=opts.LabelOpts(color="white")),
# 设置坐标轴白色
yaxis3d_opts=opts.Axis3DOpts(Faker.week_en, type_="value", axislabel_opts=opts.LabelOpts(color="white")),
grid3d_opts=opts.Grid3DOpts(
width=100, depth=100, rotate_speed=150, is_rotate=True, axislabel_opts=opts.LabelOpts(color="white")
)
)
.set_global_opts(
visualmap_opts=opts.VisualMapOpts(max_=30, min_=0, range_color=Faker.visual_color),
title_opts=opts.TitleOpts(title="弹簧3D折线图", title_textstyle_opts=opts.TextStyleOpts(color="#FFFFFF")),
)
)
return c
def Summary(): # 汇总图
page = Page()
page.add(
tab("班级:\t22数据本\n学号:\t2022402223\n姓名:\t郑尔豪", "#2CB34A", 20),
bar(),
tab("数据可视化大屏", "#2CB34A", 30),
scatter3D(),
radius(),
line(),
geo(),
scatter()
)
return page
def Zhizuo(): # 修改布局
with open("2021402156Mrtian.html", "r+", encoding='utf-8') as html:
html_bf = BeautifulSoup(html, 'lxml')
divs = html_bf.select('.chart-container')
divs[0]["style"] = "width:10%;height:10%;position:absolute;top:0;left:2%;"
divs[1]["style"] = "width:40%;height:40%;position:absolute;top:12%;left:0;"
divs[2]["style"] = "width:35%;height:10%;position:absolute;top:2%;left:30%;"
divs[3]["style"] = "width:30%;height:40%;position:absolute;top:10%;left:36%;"
divs[4]["style"] = "width:40%;height:35%;position:absolute;top:12%;left:55%;"
divs[5]["style"] = "width:30%;height:35%;position:absolute;top:55%;left:2%;"
divs[6]["style"] = "width:60%;height:50%;position:absolute;top:45%;left:15%;"
divs[7]["style"] = "width:35%;height:40%;position:absolute;top:55%;left:60%;"
body = html_bf.find("body")
body[
"style"] = "background-image: url(https://tse1-mm.cn.bing.net/th/id/OIP-C.BLVs3j-wt2XVI2NdeI9FPAHaDt?w=342&h" \
"=175&c=7&r=0&o=5&pid=1.7);background-size:cover" # 背景颜色
html_new = str(html_bf)
html.seek(0, 0)
html.truncate()
html.write(html_new)
if __name__ == '__main__': # 主函数
Summary().render('xxx.html')
Zhizuo()
根据这些代码,完成一个讲解、解析ppt内容 |
|