echarts柱状图的X轴label过长被重叠覆盖

文章目录

x轴的刻度标签字符过长

渲染ecahrt柱状图时,x轴标签很多,导致正常渲染所有标签时标签会重复叠加在一块

添加数据区域缩放dataZoom

在图表的配置项options中添加dataZoom配置项

c 复制代码
const options={
	...
	dataZoom:[{
		type:'slider',//滑动条类型
		show:true,
		height: 10,//滑动条的高度
		bottom: 20,//距离容器的距离
		start: 0,//起始位置百分比,及窗口起始位置所在的百分比
		//例如在超出渲染区域时,首次想看到较为靠后的区域位置数据,就可以设置为10、20等,如果首次进来就要看到第一条的,设置为0即可
		end: Math.min(100, 2240 / totalWidth * 100),
		//这里2240是渲染区域的宽度,按照实际数据写即可,totalWidth是计算出的再不影响显示情况下渲染完所有的x轴标签需要用到的总宽度
		//end的值也可以计算得到
		end: endPercentage,
		xAxisIndex:[0],//dataZoom组件控制的x轴,可以设置数组,表示这个组件控制不同的轴,设置数字时,表示控制一个轴,最好指定
		filterMode:'filter',//内部设置轴的显示效果
		//属性值有filter、weakFilter、empty、none具体区别官网描述的很详细,这里就不赘述了
		//还有很多其他的属性,可以随需要进行添加
	}],
	...
	//x轴的标签放不下,也可以给label设置旋转或者换行
	xAxis:{
		axisLabel:{
			...
			rotate:45,
			// 如果文字太长,可以自动换行
            formatter: function(value) {
              // 每8个字符换行(可根据实际字体大小调整)
              const maxCharsPerLine = 8 //可设置几个字符一换行
              if (value.length > maxCharsPerLine) {
                const lines = []
                for (let i = 0; i < value.length; i += maxCharsPerLine) {
                  lines.push(value.substring(i, i + maxCharsPerLine))
                }
                return lines.join('\n')
              }
              return value
            },
		}
	}
}
c 复制代码
 // 设置x轴每个类目的宽度
      const barWidth = 100 // 每个柱子的宽度
      const barGap = 10 // 柱子之间的间距
       //labelWidths是x轴要渲染的每个标签字符串所占宽度,labels中的每个元素就是x轴的标签
      const labelWidths = this.labels.map(item =>
         String(item).length * 12
      ) || []
       // 重新计算totalWidth
      const totalWidth = labelWidths.reduce((sum, width, index) => {
        return sum + Math.max(width, barWidth) + barGap
      }, 100) // 加上一些额外的间距
      // 获取当前容器宽度
      const containerWidth = this.$refs.echartsRef?.clientWidth || 2240
      // 计算结束位置百分比
      const endPercentage = Math.min(100, (containerWidth / totalWidth) * 100)

窗口resize变化时要重新计算渲染

c 复制代码
//常用写法,给window添加resize的事件监听,窗口大小变化时,去重新渲染图表
mounted(){
	window.addEventListener('resize',()=>{
        if(this.timer){
          clearTimeout(this.timer)
        }
        //添加个防抖
        this.timer=setTimeout(()=>{
          this.resizeEcharts()
        },200)
      })
}
beforeDestroy() {
    if(this.timer){
      clearTimeout(this.timer)
      this.timer=null
    }
    window.removeEventListener('resize',this.resizeEcharts)
  },
methods:{
	resizeEcharts(){
	  //echartsInstace是初始化的图表实例
     //if(echartsInstace){
	   //  echartsInstace.resize()
      //}
		 //上述是简易的改变图表尺寸
		 //如果有缩放区域组件,还要去更新dataZoom
      const container = this.$refs.echartRef
      const newWidth = container.clientWidth//现容器宽度
		 // 只有当宽度真正变化时才更新,实际也相当于做了节流,当宽度变化超过10时才重新渲染,减少渲染次数
		 // 只有当宽度真正变化时才更新
      if (Math.abs(newWidth - this.containerWidth) > 10) {
        this.containerWidth = newWidth
	 // 设置x轴每个类目的宽度
      const barWidth = 100 // 每个柱子的宽度
      const barGap = 10 // 柱子之间的间距
       //labelWidths是x轴要渲染的每个标签字符串所占宽度,labels中的每个元素就是x轴的标签
      const labelWidths = this.labels.map(item =>
         String(item).length * 12
      ) || []
       // 重新计算totalWidth
      const totalWidth = labelWidths.reduce((sum, width, index) => {
        return sum + Math.max(width, barWidth) + barGap
      }, 100) // 加上一些额外的间距
      // 计算结束位置百分比
      const endPercentage = Math.min(100, (newWidth/ totalWidth) * 100)
      //更新dataZoom
      echartsInstace.dispatchAction({
      	type: 'dataZoom',
      	dataZoomIndex:0,
      	start:0,
      	end:endPercentage
      })
		// 调整图表大小
      echartsInstace.resize()
	}
}

以上是关于x轴label标签过多过长导致标签叠加显示的配置项设置,如有问题或者有别的解决方案的欢迎大家评论指出~

相关推荐
mCell8 小时前
AI 时代 SVG 画图的潜力
前端·agent·svg
我命由我1234513 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
Hopebearer_14 小时前
页面突然只剩 DOM?一次静态资源版本错配排查
前端·部署
抱抱宝14 小时前
Agent-study项目教程(03):手写 Mini-ReAct Agent(不依赖框架)
javascript·人工智能·gpt·react.js·prompt·agent
东风破_15 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
用户9385156350715 小时前
Next.js 笔记系统(二):Redis 数据服务与侧边栏组件拆分实战
javascript·全栈
java1234_小锋16 小时前
Vue3专题 - 组件基础
vue.js·vite
圣殿骑士-Khtangc16 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
BigTopOne17 小时前
【ijkplayer】 硬解码流程
前端
kyriewen18 小时前
DeepSeek Harness开源第一天我就上手了——和Claude Code的差距比想象中大
前端·ai编程·deepseek