目标:
本篇文章是介绍使用 Echarts 时设置 X 轴上的刻度只显示最大值和最小值, 不显示其他的刻度这个我在做项目的过程中遇到的一个需求, 我花费了很长的时间才找到的一种解决办法, 希望对后面遇到此坑的朋友有些许帮助, 废话不多说, 下面介绍实现过程
Step 1: 显示 Echarts 图
在页面上引入 Echarts 插件, 并将 Echarts 图显示在页面上, 代码如下:
- <script type="text/javascript" src="__JS__/echarts.min.js">
- </script>
- <script>
- var myChart0100 = echarts.init(document.getElementById('index_main0100'));
- option0100 = {
- backgroundColor: '#fff',
- title: {
- show: true,
- text: name,
- textStyle: {
- fontWeight: 'normal',
- fontSize: 15,
- color: '#666666'
- },
- top: '13',
- left: 'center'
- },
- tooltip: {
- trigger: 'axis',
- axisPointer: {
- lineStyle: {
- color: '#cfd8dc',
- type: 'dashed',
- }
- }
- },
- grid: {
- left: '3%',
- right: '4%',
- bottom: '3%',
- containLabel: true
- },
- xAxis: [{
- type: 'category',
- boundaryGap: false,
- axisTick: {
- show: false
- },
- axisLine: {
- show: true,
- lineStyle: {
- color: '#f1f1f1',
- type: 'solid',
- },
- },
- splitLine: {
- show: true,
- interval: 'auto',
- lineStyle: {
- color: '#f1f1f1',
- type: 'solid',
- }
- },
- axisLabel: {
- margin: 10,
- textStyle: {
- color: '#999',
- fontSize: 12,
- }
- },
- data: npvincrementTime
- }],
- yAxis: [{
- type: 'value',
- scale: 'true',
- axisTick: {
- show: false
- },
- axisLine: {
- show: true,
- lineStyle: {
- color: '#f1f1f1',
- type: 'solid',
- },
- },
- axisLabel: {
- margin: 10,
- textStyle: {
- fontSize: 12,
- color: '#999999'
- }
- },
- splitLine: {
- lineStyle: {
- color: '#f1f1f1',
- type: 'solid',
- }
- }
- }],
- series: [{
- name: '收益走势',
- type: 'line',
- smooth: true,
- symbolSize: 10,
- showSymbol: true,
- lineStyle: {
- normal: {
- width: 1.5,
- color: lineColor,
- }
- },
- areaStyle: {
- normal: {
- color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
- offset: 0,
- color: shadowColor
- },
- {
- offset: 0.8,
- color: shadowColor
- }], false),
- shadowColor: shadowColor,
- shadowBlur: 10
- }
- },
- itemStyle: {
- normal: {
- color: 'rgb(255, 255, 255)',
- borderColor: borderColor,
- borderWidth: 1.5
- }
- },
- data: npvincrementIncrement
- },
- ]
- };
- myChart0100.setOption(option0100);
- </script>
效果图:
Step 2: 在 Echarts 手册中查询 X 轴的配置项
这里需要先查询 Echarts 配置项的手册, 根据手册对配置项进行设置, Echarts 手册网址, 因为我们需要修改 X 轴, 所以查询到 X 轴的配置项, 如下图:
在手册中找到: xAxis.axisLabel 这个对象, 是用来设置 x 坐标轴刻度, 到这一步已经成功了一大半了, 下面我说一下自己的思路: 只显示最大和最小值, 那只需要将配置项中的坐标轴刻度间隔的值设置大些, 这样就能显示出来最大和最小值, 可是如果有多个数据同时显示的时候, 每个数据最大和最小刻度对应的间隔是不一样, 如果设置成最大的间隔, 那么间隔小的数据中最大刻值就不能显示出来了, 因此可以强制显示出最大和最小的刻度, 然后将刻度的间隔设置成很大的一个值, 这样就会避免各个数据中最大和最小刻度间隔不一致的问题了
Step 3: 强制显示最大和最小刻度, 并将刻度间隔设置成大值
根据上面的思路, 在 axisLabel 配置项中增加配置:
- interval: 100000,
- showMinLabel: true,
- showMaxLabel: true,
修改完 Echarts 图的配置项值的 axisLabel 的完整值如下:
- axisLabel: {
- margin: 10,
- interval: 100000,
- showMinLabel: true,
- showMaxLabel: true,
- textStyle: {
- color: '#999',
- fontSize: 12,
- }
- },
欢迎指正!!!
来源: https://juejin.im/post/5a9aa3c9f265da239235cd1e