后端代码:
@Controller
@RequestMapping("/echart")
public class EchartsController {
/**
* 饼图 测试用例
* @return
*/
@RequestMapping(value = "/pie",method = RequestMethod.POST,
produces = {"application/text;charset=utf-8"})
@ResponseBody
public String pie(){
//需要的数据
String title = "搜索引擎统计";
String[] searchs = {"百度","必应","豆瓣","搜狗"};
int[] datas = {123,456,789,555};
//创建option对象
Option option = new GsonOption();
//设置标题 二级标题 标题位置
option.title().text(title).subtext("二级标题").x("center");
//设置工具栏 展示 能标记
option.toolbox().show(true).feature(Tool.mark);
//设置显示工具格式
option.tooltip().show(true).formatter("{a}</br>{b}:{c}/个");
//设置图例 图例位置 图例对齐方式 竖列对齐
option.legend().data(searchs).x("left").orient(Orient.vertical);
//填充数据
Pie pie = new Pie();//创建饼图对象
//设置饼图的标题 半径、位置
pie.name(title).radius("55%").center("50%","50%");
//填充数据
for(int i = 0; i < searchs.length; i++){
Map<String,Object> map = new HashMap<>();
map.put("value",datas[i]);//填充饼图数据
map.put("name",searchs[i]);//填充饼图数据对应的搜索引擎
pie.data(map);
}
option.series(pie); //设置数据
return option.toString();
}
}
返回的json数据:
{
"title": {"text": "搜索引擎统计", "subtext": "二级标题", "x": "center"},
"toolbox": {
"feature": {
"mark": {
"show": true,
"title": {"markUndo": "删除辅助线", "markClear": "清空辅助线", "mark": "辅助线开关"},
"lineStyle": {"color": "#1e90ff", "type": "dashed", "width": 2}
}
}, "show": true
},
"tooltip": {"formatter": "{a}</br>{b}:{c}/个", "show": true},
"legend": {"orient": "vertical", "data": ["百度", "必应", "豆瓣", "搜狗"], "x": "left"},
"series": [{
"center": ["50%", "50%"],
"radius": "55%",
"name": "搜索引擎统计",
"type": "pie",
"data": [{"name": "百度", "value": 123}, {"name": "必应", "value": 456}, {
"name": "豆瓣",
"value": 789
}, {"name": "搜狗", "value": 555}]
}]
}
前端代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
//一定要指定div的高度和宽度以便能撑起图标
<div id="echart"style="height:300px;width:600px;>
</div>
<script src="/static/jquery.min.js"></script>
<script src="/static/echarts.min.js"></script>
<script>
//图表的初始化
var echarts = echarts.init(document.getElementById('echart');
initEcharts();
function initEcharts(){
echarts.clear();
echarts.showLoading({text: '正在努力的读取数据中...'});
$.ajax({
url:"/echarts/pie",
type:"post",
success:function(data){
var option = eval("("+data+")");
echarts.setOption(option);
echarts.hideLoading();
}
})
}
</script>