Echarts人口金字塔
Echarts 人口金字塔
先看一下设计效果图,如下图;这里完全实现这个效果是不好实现的,个人觉得有两个难点,一个是 Y 轴的列标,还有就是渐变效果,尝试了一下没有成功,就打住了
然后看一下最终的效果图,虽然有点丑,理想和现实总是有差距的对吧,废话不多说,下面看看我实现的心路历程吧。
获取数据
数据来源也是自己获取的,在数据库表中,只存了用户的出生年月日,也就是说,我需要根据当前系统时间,和存在库表中的时间计算年龄,然后根据算出来的年龄和性别分组,得到 count 即可,以下是我使用 mssql 数据库的查询语句,需要查看的就是 sql 中的 datediff()这个方法,百度一下很多说明的,没有什么难点,很简单理解的 sql 语句
1 | SELECT sex,CASE when datediff(year,Birthday,getdate()) <= 19 then '20岁以内'when datediff(year,Birthday,getdate()) between 20 and 29 then '20-30'when datediff(year,Birthday,getdate()) between 30 and 39 then '30-40'when datediff(year,Birthday,getdate()) between 40 and 49 then '40-50'when datediff(year,Birthday,getdate()) between 50 and 59 then '50-60'when datediff(year,Birthday,getdate()) between 60 and 69 then '60-70'when datediff(year,Birthday,getdate()) between 70 and 79 then '70-80'when datediff(year,Birthday,getdate()) between 80 and 89 then '90-90'else '90岁以上' end as 年龄段,count(*) as 年龄段人数from User WHERE DeleteStatus = 0group byCASE when datediff(year,Birthday,getdate()) <= 19 then '20岁以内'when datediff(year,Birthday,getdate()) between 20 and 29 then '20-30'when datediff(year,Birthday,getdate()) between 30 and 39 then '30-40'when datediff(year,Birthday,getdate()) between 40 and 49 then '40-50'when datediff(year,Birthday,getdate()) between 50 and 59 then '50-60'when datediff(year,Birthday,getdate()) between 60 and 69 then '60-70'when datediff(year,Birthday,getdate()) between 70 and 79 then '70-80'when datediff(year,Birthday,getdate()) between 80 and 89 then '90-90'else '90岁以上' END,sex |
前端 echarts 实现
我结合网上查找的实例,和官网的 api 参数说明,凑出了最后的效果,话不多说,直接上代码
1 | ajaxFormData('@Url.Action("GetTalentsAgesGrade", "Home")', {}, |
最后简单总结下前端实现的思路,其实就是一个柱状图的实现,让其分组结果左右显示,最重要的是左边,我让其 value 全部为负数了,这样就能显示在左边了,最后鼠标移入和图形显示为什么不是负数呢,建议看一下 tooltip.formatter()和 xAxis.formatter()这里的重写方法,echarts 的官方说明文档是有详细说明的。最后比较坑的点是,如果左右最大值不一样的话,y 轴就没在整个图的中间,这里我的解决办法,是 xAxis.max 设置的值是,这两组数据的最大值。
我做的还原度不是很好,但对没接触过 echarts 的我来说又是一次小成长,在学习的路上,我一直是捡贝壳的小男孩。