Echarts —— 利用配置项美化图表

1,343 阅读2分钟

基于一个统计的需求,选择了echarts可视化图表库进行开发,由于echarts默认的样式不符合UI规范,所以需要调整配置项的参数来进行美化,这里记录一下常用的参数

1. yAxis、xAxis坐标轴(x轴同理)

yAxis: {
  // 坐标轴显示内容
  axisLabel: {
    formatter(value, index) {
      return value + '%'
    }
  },
  // 坐标轴样式
  axisLine: {
    lineStyle:{
      color: '#9296A8',
      width: 1,
      type: 'solid'
    }
  },
  // 网格样式
  splitLine: {
    show: true,
    lineStyle:{
      color: ['#E0E7FF'],
      width: 1,
      type: 'solid'
    }
  }
},

2. grid设置图表空白区域

默认的空白区域可能是不符合设计图的,所以多数需要调整

grid: {
  x: 30,   // 左
  y: 70,   // sshang 
  x2: 30,  //  右
  y2: 10
}

3. legend图例组件

legend: {
  show: true,
  right: 50,      //可设定图例在左、右、居中
  top: 15,     //可设定图例在上、下、居中
  itemHeight: 10,
  data: [
    {
      name: 'aaa',
      // name对应的icon,有'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow', 'none',也可以自定义
      icon: "circle" 
    },
    {
      name: 'bbb',
      icon: "circle"
    },
    {
      name: 'ccc',
      icon: "circle",
    },
    'ddd',
    'eee'
  ],
  // 文字颜色
  textStyle:{
    fontSize: 12,
    color: "#9296A8"
  }
}

4. series系列列表

// 折线图
series: [
  {
  	name: 'xxx',
    type: 'line',
    smooth: true,   // 是否是曲线
    // 区域渐变色
    areaStyle: {
      color: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [
          {
            offset: 0,
            color: 'rgba(140, 84, 255, 0.4)', // 0% 处的颜色
          },
          {
            offset: 1,
            color: 'rgba(140, 84, 255, 0)' // 100% 处的颜色
          },
        ],
        global: false // 缺省为 false
      }
    }
  }
]
// 柱状图
series: [
  {
  	name: 'xxx',
    type: 'bar',
    barWidth: 7,   // 柱状图宽度
    barGap: 1,  // 柱状图间隔
    itemStyle: {
      normal: { // 平时
        barBorderRadius: [10, 10, 0, 0] // 设置圆角
      },
      emphasis: { // 被选中
        barBorderRadius: [10, 10, 0, 0] // 设置圆角
      }
    }
  }
]
// 饼图
series: [
  {
  	name: 'xxx',
    type: 'pie',
    hoverOffset: 5,  // 选中突起高度
    radius: [60, 75], // 设置成环图
    itemStyle: {
      emphasis: {
        // 设置扇形的阴影
        shadowBlur: 15,
        shadowColor: 'rgba(146, 150, 168, 0.3)',
        shadowOffsetX: -5,
        shadowOffsetY: 5
      }
    }
  }
]

5. tooltip提示框组件

tooltip: {
  show: true,
  trigger: 'item',
  // 这里返回一个字符串,echarts会解析成html,所以我们可以自己定义样式
  formatter: (params) => {
    let { name = '', percent, value } = params,
    let str = `<div>${name}</div><div>${value}</div>`
    return str
  },
  // 这里可以改变弹框的位置,同时也可以利用 dom 自定义弹框的样式
  position: (point, params, dom, rect, size) => {
    var marginW = Math.ceil(size.contentSize[0]/2)
    var marginH = Math.ceil(size.contentSize[1]/2)
    dom.style.marginLeft = `-${marginW}px`
    dom.style.marginTop = `-${marginH}px`
    dom.style.backgroundColor = 'transparent'
    dom.style.textAlign = 'center'
    return ['50%', '50%']
  },
  alwaysShowContent: true, // 始终展示弹框内容
}