最近因为工作需求需要做一个折线图图表,总结了一下实现的时候遇到的问题,下方举例为折线图,适用大多数图表参考
-
Y轴显示不全
- 设定grid下的containLabel值为true即可
- 官方文档的解释是这样的
grid 区域是否包含坐标轴的刻度标签。
- containLabel 为
false
的时候:
grid.left
grid.right
grid.top
grid.bottom
grid.width
grid.height
决定的是由坐标轴形成的矩形的尺寸和位置。- 这比较适用于多个
grid
进行对齐的场景,因为往往多个grid
对齐的时候,是依据坐标轴来对齐的。- containLabel 为
true
的时候:
grid.left
grid.right
grid.top
grid.bottom
grid.width
grid.height
决定的是包括了坐标轴标签在内的所有内容所形成的矩形的位置。- 这常用于『防止标签溢出』的场景,标签溢出指的是,标签长度动态变化时,可能会溢出容器或者覆盖其他组件。
修改前的效果:左侧紧凑,下方显示不全
修改后的效果:
-
给折线图下方区域添加渐变背景色
- 可以直接设定series下的areaStyle对其进行配置达到自己想要的效果,后附效果图
-
series: [ { //smooth是否为曲线 smooth: true, type: "line", areaStyle: { normal: { //LinearGradient线性渐变,可以设置挡位颜色达到渐变的效果 color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: "#D7EBFE" }, { offset: 0.5, color: "#E7F2FD" }, { offset: 1, color: "#F7FAFE" }, ]), }, }, data: value, }, ], };
-
响应式图表
-
为了方便图表显示,宽度使用了100%,直接取到父盒子的宽度,当然父盒子也是做了响应式处理的,所以当页面发生改变,父盒子也会跟随改变,但图表并不会发生改变。
-
处理方式就是,在echarts中给我们提供了resize方法,我们只需要监听屏幕变化然后调用即可
-
window.addEventListener("resize",()=>myChart.resize())
-
-
这里是整部分的完整代码
-
<template> <div> <div id="right"> <el-row :gutter="24"> <el-col :span="22" :offset="1" ><div id="ChartBox" ref="ChartBox"></div ></el-col> </el-row> </div> </div> </template> <script> export default { name: "echartVue", data() { return { Xaxis:["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], Yaxis:[120, 132, 101, 134, 90, 230, 210], }; }, created() {}, mounted() { this.getChart( this.Xaxis,this.Yaxis ); window.onresize = () => { // console.log('浏览器', this.$refs.domF.offsetWidth) this.getChart( this.Xaxis,this.Yaxis ); } }, methods: { getChart(key, value) { var myChart = this.$echarts.init(this.$refs.ChartBox); var option; option = { title: { text: "折线图颜色渐变", }, // 鼠标移入的气泡提示框 item或axis tooltip: { trigger: "item", }, grid: { left: "3%", right: "4%", bottom: "3%", containLabel: true, }, // toolbox 是否可以下载当前图表 toolbox: { feature: { saveAsImage: {}, }, }, xAxis: { type: "category", // boundaryGap 边界差距 建议false,比较美观 boundaryGap: false, data: key, }, yAxis: { type: "value", }, series: [ { //smooth是否为曲线 smooth: true, type: "line", areaStyle: { normal: { //LinearGradient线性渐变,可以设置挡位颜色达到渐变的效果 color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: "#D7EBFE" }, { offset: 0.5, color: "#E7F2FD" }, { offset: 1, color: "#F7FAFE" }, ]), }, }, data: value, }, ], }; option && myChart.setOption(option); window.addEventListener("resize",()=>myChart.resize()) }, }, }; </script> <style scoped> #right { width: 70%; height: 100vh; float: right; background-color: gray; } #ChartBox { width: 100%; height: 400px; margin: 20px auto; background-color: #fff; border-radius: 2%; box-shadow: 0px 0px 5px #f3f7fc; overflow: visible; } </style>