A way to wrap and align the legend in echarts

Foreword:

In statistical graphs, there are often many legends. At this time, there is a possibility that one line cannot fit, and I think of wrapping. Of course, the legend will automatically wrap when one line cannot fit, but. . . Is he right? ! So I ran to ask the product whether it would be okay. The product said: How can it be unequal? ? ? (Black question mark) I said that it can be aligned, but it has to be configured (actually, I just want to do this in my heart), but in the end I still satisfy her and align them all! !

Before talking about my method, let's take a look at the default line break:

The reason for the misalignment may be because the default legend spacing is fixed, and the size of each legend is adaptive by the font (guess), but this is not very important. I also saw that there are many other methods on the Internet. There are other methods for grouping the legends. I mainly find it troublesome, so I found a fairly simple method. Not much to say, get talent (method)! !

The key idea:

Get the total width of the legend, and then divide it by how many lines you want to set to calculate the width of a legend. It sounds simple. The total width of getting the legend is basically the size of the echarts canvas, which is easy to get. Assuming it is allWidth, assuming that a row displays 10, then the width of each legend is:

width = allWidth / 10

The legend is composed of icon and text, and their respective widths can be set separately. The main reason for the misalignment is that the number of texts is not fixed, so just set the text width to be the same, you can align! ! The following code:

Key code:

// echarts 的 legend配置 
legend: {
     data: legendData,
     icon: 'circle',
     formatter: '{a|{name}}',
     itemGap: 0,
     left: 'center',
     textStyle: {
        color: "#1B1B4E",
        padding: [0, 0, 0, 0],
        rich:{
           a: {
             width: (allWidth - 200) / 10,
             height:38,
             fontSize: 12
           },
        }
    },
 },

Realization effect: 

Description:

For the rich text style of the text used here, see echarts for details . In addition, I subtracted 200 on the basis of allWidth. This is set according to my actual situation. My understanding is to subtract all the width of a line of icon. Because we set the width of the text, we need to subtract the width of the icon. Calculation. Personally, it is quite simple, and I hope it will help you.

Guess you like

Origin blog.csdn.net/DZY_12/article/details/108792635