echarts 可以设置的echarts单位的偏移位置吗?
之前是知道echarts的X和Y是可以设置单位的。 但是设置单位的位置一直不好调整。 现在有时间,我们会回答一下上面标题的问题? echarts 可以设置X和Y轴单位的偏移位置吗?答案是可以的。 通过 nameTextStyle 这个属性来处理
echarts柱状图Y轴上设置单位
yAxis: [{ type: 'value', name: '(个)', //单位 nameLocation: 'end', // (单位个也就是在在Y轴的最顶部) //单位的样式设置 nameTextStyle: { color: "green", //颜色 padding: [15, 20, 15, 0], //间距分别是 上 右 下 左 }, }] 当我们设置后,就会出现下面图的样式
为什么上面这两张图单位间距不一样
细心的小伙伴发现了。这两张图的间距是不一样的。 第一张的距离左边间距小。第二张图距离左侧间距较大。 那是什么原因导致两张图的间距不一样的呢? 有的小伙伴,可能会说:是你设置的间距不一样? 我可以很负责的说:不是的。设置的是同样的间距。 有些小伙伴可能会说:有没有可能是Y轴的数据不一样导致的? 恭喜这位小伙伴,猜对了。就是Y轴的数据大小不同而导致间距不一样的。
那有没有办法让单位距离左侧的间距是一样的呢
我在看echarts官方文档的时候(https://echarts.apache.org/zh/option.html#xAxis.nameTextStyle.align) 发现了 align 属性。但是使用这个属性后 align:'left' 仍然是不可以办到的。 也就是说:单位距离左侧的间距是一样? 这个是办不到的。
Y轴数据较小的情况
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script> </head> <body> <div style="width: 600px;height: 400px;background:#ccc"></div> <script> var mCharts = echarts.init(document.querySelector('div')) var option = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: [{ type: 'category', data: ['1111', '2232', '2332', '2123'], axisTick: { alignWithLabel: true }, }], yAxis: [{ type: 'value', // 新增单位 name: '(个)', nameLocation: 'end', // 在头部(也就是在在X轴的最底部) //间距 nameTextStyle: { // align: 'center', color: "green", // verticalAlign: 'top', // 这个间距 分别是 上下右左 padding: [15, 20, 15, 0], }, }], series: [{ name: '直接访问', type: 'bar', barWidth: '60%', data: [11, 41, 51, 16, 71] }] }; mCharts.setOption(option) </script> </body> </html>
Y轴数据较大的情况
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script> </head> <body> <div style="width: 600px;height: 400px;background:#ccc"></div> <script> var mCharts = echarts.init(document.querySelector('div')) var option = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: [{ type: 'category', data: ['1111', '2232', '2332', '2123'], axisTick: { alignWithLabel: true }, }], yAxis: [{ type: 'value', // 新增单位 name: '(个)', nameLocation: 'end', // 在头部(也就是在在X轴的最底部) //间距 nameTextStyle: { // align: 'center', color: "green", // verticalAlign: 'top', padding: [15, 20, 15, 0], }, }], series: [{ name: '直接访问', type: 'bar', barWidth: '60%', data: [11123, 41123, 51123, 16122, 712341] }] }; mCharts.setOption(option) </script> </body> </html>