记录下用echarts3实现的特殊柱状图
实现效果如下:图片描述的是不同年龄段下的男女占比。
代码如下
一、JSP页面关键代码:
二、JS代码(xxxx.js):
//获取contextpath
var pathName = document.location.pathname;
var index = pathName.substr(1).indexOf("/");
var contextPath = pathName.substr(0, index + 1);
$.ajax(
{
type : "POST",
url : contextPath + '/www/getChartData.do?' + new Date().getTime(),
data : {},
dataType : "json",
async : false,
success : function(data) {
initChart(data);
}
}
);
function initChart(data) {
var myChart = echarts.init(document.getElementById('ageChart'));
var option = {
color : [ '#075356', '#4e2b63' ],
legend : [ {
itemWidth : 10,
itemHeight : 10,
align : 'left',
right : '45',
textStyle : {
fontSize : 10,
color : '#cccece',
},
itemStyle : {
borderColor : '#04a3a7',
borderWidth : 1
},
data : [ '男' ]
},
{
itemWidth : 10,
itemHeight : 10,
align : 'left',
right : 10,
textStyle : {
fontSize : 10,
color : '#cccece',
},
itemStyle : {
borderColor : '#b527ae',
borderWidth : 1
},
data : [ '女' ]
},
],
grid : {
left : '15',
right : '15',
bottom : '5',
top: '20',
containLabel : true
},
xAxis : [
{
type : 'value',
max : 100,
min : -100,
splitLine : {
show : false
},
axisLine : {
show : false
},
axisTick : {
show : false
},
axisLabel : {
fontSize:10,
color : '#3ec4cf',
show : true,
formatter : function(value, index) {
var texts = [ value, '%' ];
if (value < 0) {
texts = [ -value, '%' ];
}
if (texts.join('') === '0%') {
return 0;
}
return texts.join('');
}
}
}
],
yAxis : [
{
type : 'category',
axisLine : {
show : false
},
axisLabel : {
show : false
},
axisTick : {
show : false
},
splitLine : {
show : false
},
data : data.category
}
],
series : [
//为了让两边的条形图在中间线分开设置的辅助数据
{
name : '辅助',
type : 'bar',
stack : '总量',
itemStyle : {
normal : {
barBorderColor : 'rgba(0,0,0,0)',
color : 'rgba(0,0,0,0)'
}
},
data : [ -1, -1, -1, -1, -1, -1 ]
},
{
name : '男',
type : 'bar',
stack : '总量',
//barCategoryGap : '60%',
label : {
normal : {
show : true,
formatter : '{b}',
position : 'left',
color: '#cccece'
}
},
itemStyle : {
borderColor : '#04a3a7',
barBorderRadius : [ 10, 0, 0, 10 ],
},
data : data.men
},
{
name : '辅助',
type : 'bar',
stack : '总量',
itemStyle : {
normal : {
barBorderColor : 'rgba(0,0,0,0)',
color : 'rgba(0,0,0,0)'
}
},
data : [ 1, 1, 1, 1, 1, 1 ]
},
{
name : '女',
type : 'bar',
stack : '总量',
itemStyle : {
borderColor : '#b527ae',
barBorderRadius : [ 0, 10, 10, 0 ],
},
data : data.women
}
]
};
myChart.setOption(option, true);
}
三、接口返回数据样例(js代码中getChartData.do):
--后台接口代码省略
{
"category": ["81+岁", "60-80岁", "36-59岁", "19-35岁", "8-18岁", "0-7岁"],
"men": [-1.5552, -10.4459, -38.3378, -25.7374, -2.9681, -20.9557],
"women": [1.3584, 8.4174, 28.0238, 50.1093, 1.2974, 10.7937]
}
来源:oschina
链接:https://my.oschina.net/dingyibo/blog/4287328