代码注释非常详细,做好数据转换是基本功.
以下是完整版代码
// 添加echarts柱状图
let myChart = echarts.init(d2, 'dark')
let option
//整理数据结构,讲res,data转成labes,values
//res.data:{'两室一厅':6666,'三室一厅':2011,....}
//labels:['两室一厅','三室一厅'....]
//values:[6666,2011]
let labels = []
let values = []
for (key in res.data) {
if (res.data[key] < 20) {
continue
}
labels.unshift(key)
values.unshift(res.data[key])
}
option = {
title: {
text: '北京主城区二手房源户型数量分布',
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
},
},
legend: {
right: 20,
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true,
},
xAxis: {
type: 'value',
boundaryGap: [0, 0.01],
},
yAxis: {
type: 'category',
data: labels,
},
series: [
{
name: '2011',
type: 'bar',
data: values,
},
],
}
option && myChart.setOption(option)
})
//模拟向服务器发送请求,用echarts加载数据分析结果
axios.get('./price.json').then(res => {
console.log(res)
// 整理数据结构,讲res.data转成mseris
let mseris = []
for (key in res.data) {
mseris.push({
name: key,
type: 'line',
data: res.data[key],
})
}
// 制作条形图
let myChart = echarts.init(d1, 'dark')
let option
option = {
title: {
text: '北京主城区2021年二手房价走势',
},
tooltip: {
trigger: 'axis',
},
legend: {
data: ['朝阳', '海淀', '东城', '西城'],
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true,
},
toolbox: {
feature: {
saveAsImage: {},
},
},
xAxis: {
type: 'category',
boundaryGap: false,
data: [
'一月',
'二月',
'三月',
'四月',
'五月',
'六月',
'七月',
'八月',
'九月',
'十月',
'十一月',
'十二月',
],
},
yAxis: {
type: 'value',
min: 60000,
max: 130000,
},
series: [
//我将name中的属性值用手写改了,但是改不改都一样,因为数据是动态变化的,上方已经遍历整理了数据结构
{
name: '朝阳',
type: 'line',
stack: 'Total',
data: [120, 132, 101, 134, 90, 230, 210],
},
{
name: '海淀',
type: 'line',
stack: 'Total',
data: [220, 182, 191, 234, 290, 330, 310],
},
{
name: '东城',
type: 'line',
stack: 'Total',
data: [150, 232, 201, 154, 190, 330, 410],
},
{
name: '西城',
type: 'line',
stack: 'Total',
data: [320, 332, 301, 334, 390, 330, 320],
},
],
}
//将mseries的数据赋值给series,数据可动态变化
option.series = mseris
option && myChart.setOption(option)
})
</script>
默认效果如下 ![在这里插入图片描述](https://img-blog.csdnimg.cn/8dd3bfafbd5f4d8fba48eefcd3a0269e.png)