1.JAVA
1.饼图
前端使用vue,后端使用SpringBoot
<template>
<div>
<div class="card" style="padding: 15px">
数据可视化分析:图书类型销量
</div>
<div style="display: flex; margin: 10px 0">
<div style="display: flex; margin: 10px 0">
<div style="width: 1200px;height: 600px;" class="card" id="goodsPie"></div>
</div>
</div>
</div>
</template>
<script>
import * as echarts from "echarts";
let pieGoodsOptions = {
title: {
text: '', // 主标题
subtext: '', // 副标题
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)'
},
legend: {
top: '8%',
type: 'scroll',
orient: 'vertical',
left: 'left',
pageIconColor: 'red', // 激活的分页按钮颜色
pageIconInactiveColor: 'yellow', // 没激活的分页按钮颜色
},
series: [
{
name: '', // 鼠标移上去显示内容
type: 'pie',
radius: '50%',
center: ['50%', '60%'],
data: [
{value: 0, name: ''}, // 示例数据:name表示维度,value表示对应的值
]
}
]
}
export default {
name: "Visualization",
data() {
return {
}
},
created() {
this.loadGoodsPie();
},
methods: {
loadGoodsPie(){
this.$request.get('/goods/getPie').then(res => {
if (res.code === '200') {
let chartDom = document.getElementById('goodsPie');
let myChart = echarts.init(chartDom);
pieGoodsOptions.title.text = res.data.text
pieGoodsOptions.title.subtext = res.data.subText
pieGoodsOptions.series[0].name = res.data.name
pieGoodsOptions.series[0].data = res.data.data
myChart.setOption(pieGoodsOptions);
} else {
this.$message.error(res.msg)
}
})
},
}
}
</script>
/**
* 渲染图书类型销量饼状图
*/
@GetMapping("/getPie")
public Result getPie() {
Map<String, Object> resultMap = new HashMap<>();
List<Map<String, Object>> list = new ArrayList<>();
// 获得商品分类名称为key,该分类销量为value的map
List<Goods> goodsList = goodsService.selectAll(new Goods());
Map<String, Integer> collect = goodsList.stream().filter(x -> ObjectUtil.isNotEmpty(x.getTypeId()))
.collect(Collectors.groupingBy(Goods::getTypeName, Collectors.reducing(0, Goods::getCount, Integer::sum)));
for (String key : collect.keySet()) {
Map<String, Object> map = new HashMap<>();
map.put("name", key);
map.put("value", collect.get(key));
list.add(map);
}
resultMap.put("text", "图书类型销售量统计饼图");
resultMap.put("subText", "统计维度:图书类型");
resultMap.put("name", "占比数据");
resultMap.put("data", list);
return Result.success(resultMap);
}
1.柱状图
前端使用vue,后端使用SpringBoot
<template>
<div>
<div class="card" style="padding: 15px">
数据可视化分析:店铺销量
</div>
<div style="display: flex; margin: 10px 0">
<!-- 后台主页左上部分:公告 -->
<div style="display: flex; margin: 10px 0">
<div style="width: 600px;height: 600px;" class="card" id="businessBar"></div>
</div>
</div>
</div>
</template>
<script>
import * as echarts from "echarts";
let barBusinessOptions = {
title: {
text: '', // 主标题
subtext: '', // 副标题
left: 'center'
},
xAxis: {
axisLabel:{
interval: 0,
//rotate:30,
formatter: function (name) {
return (name.length > 8 ? (name.slice(0,8)+"...") : name );
},
},
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] // 示例数据:统计的维度(横坐标)
},
yAxis: {
type: 'value'
},
tooltip: {
trigger: 'item'
},
series: [
{
data: [120, 200, 150, 80, 70, 110, 130], // 示例数据:横坐标维度对应的值(纵坐标)
type: 'bar',
itemStyle: {
normal: {
color:function(){return "#"+Math.floor(Math.random()*(256*256*256-1)).toString(16);}
},
},
}
]
}
export default {
name: "Visualization2",
data() {
return {
}
},
created() {
this.loadBusinessBar();
},
methods: {
loadBusinessBar(){
this.$request.get('/goods/getBar').then(res => {
if (res.code === '200') {
let chartDom = document.getElementById('businessBar');
let myChart = echarts.init(chartDom);
barBusinessOptions.title.text = res.data.text
barBusinessOptions.title.subtext = res.data.subText
barBusinessOptions.xAxis.data = res.data.xAxis
barBusinessOptions.series[0].data = res.data.yAxis
myChart.setOption(barBusinessOptions);
} else {
this.$message.error(res.msg)
}
})
},
}
}
</script>
/**
* 渲染店铺销量柱状图
*/
@GetMapping("/getBar")
public Result getBar() {
Map<String, Object> resultMap = new HashMap<>(); // 存取最后返回的数据
Map<String, Object> res = new HashMap<>(); // 暂存销量前5的数据
List<String> xList = new ArrayList<>(); // 店铺名称
List<Integer> yList = new ArrayList<>(); // 店铺总销量
// 获得店铺名称为key,该店铺全部销量求和为value的map
List<Goods> goodsList = goodsService.selectAll(new Goods());
Map<String, Integer> collect = goodsList.stream().filter(x -> ObjectUtil.isNotEmpty(x.getBusinessId()))
.collect(Collectors.groupingBy(Goods::getBusinessName, Collectors.reducing(0, Goods::getCount, Integer::sum)));
collect.entrySet()
.stream()
// 排序
.sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
// 截取前limitSize个
.limit(5)
.collect(Collectors.toList()).forEach(ele -> res.put(ele.getKey(), ele.getValue()));
for (String key : res.keySet()) {
xList.add(key);
yList.add((Integer) res.get(key));
}
resultMap.put("text", "店铺销售量前五统计柱状图");
resultMap.put("subText", "统计维度:店铺名称");
resultMap.put("xAxis", xList);
resultMap.put("yAxis", yList);
return Result.success(resultMap);
}
2.Python
1.折线图
import json
from pyecharts.charts import Line
from pyecharts.options import TitleOpts,LegendOpts,ToolboxOpts,VisualMapOpts,LabelOpts
# 处理数据
f_usa = open("D:/美国.txt","r",encoding="UTF-8")
usa_data = f_usa.read() # 美国的全部内容
f_jp = open("D:/日本.txt","r",encoding="UTF-8")
jp_data = f_jp.read() # 日本的全部内容
f_in = open("D:/印度.txt","r",encoding="UTF-8")
in_data = f_in.read() # 印度的全部内容
# 去掉不符合JSON规范的开头
usa_data = usa_data.replace("jsonp_1629344292311_69436(","")
jp_data = jp_data.replace("jsonp_1629350871167_29498(","")
in_data = in_data.replace("jsonp_1629350745930_63180(","")
# 去掉不符合JSON规范的结尾
usa_data = usa_data[0:-2:1] # 最后两个字符:); 不要
jp_data = jp_data[0:-2:1] # 最后两个字符:); 不要
in_data = in_data[0:-2:1] # 最后两个字符:); 不要
# JSON转为python字典
usa_dict = json.loads(usa_data)
jp_dict = json.loads(jp_data)
in_dict = json.loads(in_data)
# print(type(usa_dict))
# print(usa_dict)
# 获取trend
usa_trend_data = usa_dict['data'][0]['trend']
jp_trend_data = jp_dict['data'][0]['trend']
in_trend_data = in_dict['data'][0]['trend']
# print(trend_data)
#取日期数据,用于x轴,只去2020一年(到313结束)
usa_x_data = usa_trend_data["updateDate"][0:314]
jp_x_data = jp_trend_data["updateDate"][0:314]
in_x_data = in_trend_data["updateDate"][0:314]
# print(x_data)
#取确诊数据,用于y轴
usa_y_data = usa_trend_data['list'][0]['data'][0:314]
jp_y_data = jp_trend_data['list'][0]['data'][0:314]
in_y_data = in_trend_data['list'][0]['data'][0:314]
# print(y_data)
# 生成图表对象
line = Line()
# 添加x轴,日期公用添加一个即可
line.add_xaxis(usa_x_data)
# 添加y轴
line.add_yaxis("美国确诊人数", usa_y_data, label_opts=LabelOpts(is_show=False)) # 设置折线上不展示数字
line.add_yaxis("日本确诊人数", jp_y_data, label_opts=LabelOpts(is_show=False))
line.add_yaxis("印度确诊人数", in_y_data, label_opts=LabelOpts(is_show=False))
# 设置全局配置项,选填
line.set_global_opts(
title_opts=TitleOpts(title="2020年美日印确诊人数折线图",pos_left="center",pos_bottom="1%"), # 标题
legend_opts=LegendOpts(is_show=True), # 图例
toolbox_opts=ToolboxOpts(is_show=True), # 工具箱
visualmap_opts=VisualMapOpts(is_show=True), # 视觉映射
)
# 生成图表
line.render()
# 关闭文件对象
f_usa.close()
f_jp.close()
f_in.close()
2.全国地图
import json
from pyecharts.charts import Map
from pyecharts.options import *
f = open("D:/疫情.txt","r",encoding="UTF-8")
data = f.read() # 全部数据
f.close()
# JSON转为python字典
data_dict = json.loads(data)
# 从字典中获取省份数据
province_data_dict = data_dict["areaTree"][0]["children"]
# 组装每个省份和确诊人数为元组,封装在列表内
data_list = [] # 绘图用的列表数据
for province_data in province_data_dict:
province_name = province_data["name"]
province_confirm = province_data["total"]["confirm"]
data_list.append((province_name,province_confirm))
# print(data_list)
# 创建地图对象
map = Map()
# 添加数据
map.add("各省份确诊人数",data_list,"china")
# 设置全局配置项,选填
map.set_global_opts(
title_opts=TitleOpts(title="全国疫情地图"), # 标题
visualmap_opts=VisualMapOpts(
is_show=True, # 是否显示
is_piecewise=True, # 是否分段
pieces=[
{"min":1 , "max":99 , "label":"1-99人确诊" , "coclor":"#CCFFFF"},
{"min":100 , "max":999 , "label":"100-999人确诊" , "coclor":"#FFFF99"},
{"min":1000 , "max":4999 , "label":"1000-4999人确诊" , "coclor":"#FF9966"},
{"min":5000 , "max":9999 , "label":"5000-9999人确诊" , "coclor":"#FF6666"},
{"min":10000 , "max":99999 , "label":"10000-99999人确诊" , "coclor":"#CC3333"},
{"min":100000 , "label":"100000+人确诊" , "coclor":"#990033"},
]
), # 视觉映射
)
# 绘图
map.render("全国疫情地图.html")
3.河南省地图
import json
from pyecharts.charts import Map
from pyecharts.options import *
f = open("D:/疫情.txt","r",encoding="UTF-8")
data = f.read() # 全部数据
f.close()
# JSON转为python字典
data_dict = json.loads(data)
# 取到河南省数据
cities_data_dict = data_dict["areaTree"][0]["children"][3]["children"]
# print(cities_data_dict)
# 组装每个城市和确诊人数为元组,封装在列表内
data_list = [] # 绘图用的列表数据
for city_data in cities_data_dict:
city_name = city_data["name"]+"市"
city_confirm = city_data["total"]["confirm"]
data_list.append((city_name, city_confirm))
# 创建地图对象
map = Map()
# 添加数据
map.add("河南省疫情分布",data_list,"河南")
# 设置全局配置项,选填
map.set_global_opts(
title_opts=TitleOpts(title="河南省疫情分布地图"), # 标题
visualmap_opts=VisualMapOpts(
is_show=True, # 是否显示
is_piecewise=True, # 是否分段
pieces=[
{"min":1 , "max":99 , "label":"1-99人确诊" , "coclor":"#CCFFFF"},
{"min":100 , "max":999 , "label":"100-999人确诊" , "coclor":"#FFFF99"},
{"min":1000 , "max":4999 , "label":"1000-4999人确诊" , "coclor":"#FF9966"},
{"min":5000 , "max":9999 , "label":"5000-9999人确诊" , "coclor":"#FF6666"},
{"min":10000 , "max":99999 , "label":"10000-99999人确诊" , "coclor":"#CC3333"},
{"min":100000 , "label":"100000+人确诊" , "coclor":"#990033"},
]
), # 视觉映射
)
# 绘图
map.render("河南省疫情分布地图.html")
4.1960-2019全球GDP柱状图
from pyecharts.charts import Bar,Timeline
from pyecharts.options import *
f = open("D:/1960-2019全球GDP数据.csv","r",encoding="GB2312")
data_lines = f.readlines() # 全部数据
f.close()
# 删除第一条杂余数据
data_lines.pop(0)
# 将数据转化为字典存储
data_dict = {}
for data_line in data_lines:
year = int(data_line.split(",")[0]) # 年份
contry = data_line.split(",")[1] # 国家
gdp = float(data_line.split(",")[2]) # GDP数据
# 判断字典中有没有指定的key(年份),若有直接添加数据,没有则创建一个键值对
try:
data_dict[year].append([contry,gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([contry,gdp])
# 创建时间线对象
timeline = Timeline()
# 排序年份(每一个时间点都是一个柱状图)
sorted_year_list = sorted(data_dict.keys()) # 年份排序
for year in sorted_year_list:
data_dict[year].sort(key=lambda element:element[1],reverse=True) # 每一年的gdp排序(使用过匿名函数排序)
# 取出本年份前八的国家
year_data = data_dict[year][0:8]
x_data = []
y_data = []
for contry_gdp in year_data:
x_data.append(contry_gdp[0]) # 国家
y_data.append(contry_gdp[1] / 100000000) # 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")) # y轴在右边
# 翻转x,y轴
bar.reversal_axis()
# 设置每一年图表的标题
bar.set_global_opts(
title_opts=TitleOpts(title=f"{year}年全球前八GDP柱状图")
)
# 添加数据
timeline.add(bar,str(year))
# 设置时间线自动播放
timeline.add_schema(
play_interval=1000,
is_timeline_show=True,
is_auto_play=True,
is_loop_play=False
)
# 绘图
timeline.render("1960-2019全球GDP柱状图.html")
3.数据资源下载
Python可视化案例数据资源-CSDN文库
可以点个免费的赞吗!!!