All Products
Search
Document Center

Quick BI:example: create an echarts chart

Last Updated:Dec 13, 2024

This article will introduce the development of a custom component based on echarts in Quick BI.

Example

效果图

Step 1: Create an application

  1. Create a custom component project and install dependencies after the project is created.

    For more information, see Quick start.

    npm init qbi-app myEcharts
    cd myEcharts
    yarn
  2. On the, follow the instructions in the following figure to register the component.

    image.png

    Note

    Select Professional Mode.

    For more information about online editing, see Tutorial: Quickly insert the echarts code in online editing mode.

  3. Install echarts.

    1. Run the following command to install the echarts type:

      yarn add -D @types/echarts
    2. Use one of the following methods to install echarts:

      • Third-party Alibaba Cloud Content Delivery Network introduction: This mode can improve the loading performance.

        Method: Enter the echarts Alibaba Cloud Content Delivery Network address in the Dependent Third-party Library section of the Edit Custom Component dialog box.

        image

        Set the webpack.config.js under the project root directory and add a externals configuration.

         // webpack.config.js
         externals: {
            lodash: '_',
            react: 'React',
            'react-dom': 'ReactDOM',
            moment: 'moment',
            echarts: 'echarts', // Add a new item.
          },
      • npm installation: install by npm or yarn.

        yarn add echarts
  4. On the Components page, find the component that you want to debug and click the Debug icon.

    image..png

    The system automatically jumps to the corresponding dashboard. You can debug the dashboard as required. For more information, see Debug components.

Step 2: Configure meta

The meta configuration includes the configurations of the data panel and style panel.

Configure Data Panel

In meta.ts, dataSchema can customize the way the chart is fetched according to their needs. In most cases, you can directly modify the metadata created in the template project. Common modifications include:

  • areaName: the displayed name of the field

  • required: specifies whether the field is required.

  • maxColumn: the maximum number of fields that can be dropped.

Assume that you need to display one dimension and three measures. You only need to change the corresponding maxColumn. The configuration example is as follows:

// meta.ts
const componentMeta: Interfaces.ComponentMeta = {
  propsSchema: {
    dataSchema: {
      areas: [
        {
          id: "drill",
          name: "Drillthrough /Dimension",
          queryAxis: "drill",
          rule: {
            fieldTypes: ["dimension"],
            required: false, // Indicates whether the field is required to update the chart.
            /**Limit quantity * /
            maxColNum: 3,
          },
        },
        {
          id: "area_row",
          name: "Dimension",
          queryAxis: "row",
          rule: {
            fieldTypes: ["dimension"],
            maxColNum: 1, // The maximum number of fields that are allowed.
            required: true, // Specifies whether the update icon is required.
          },
        },
        {
          id: "area_column",
          name: "Measure",
          queryAxis: "column",
          rule: {
            fieldTypes: ["dimension", "measure"],
            maxColNum: 3, // The maximum number of fields that are allowed.
            required: true, // Specifies whether the update icon is required.
          },
        },
        {
          id: "filters",
          name: "filter", // The name of the filter.
          queryAxis: "filters",
          rule: {
            fieldTypes: ["dimension", "measure"],
            required: false,
          },
        },
      ],
      resultDisplay: {
        /**Limit the number of entries * /
        upLimit: 1000,
      },
    },
  },
};
                

You can generate a data panel, as shown in the following figure. 配置面板

Configure Style Panel

styleSchema the configuration used to define the style panel. You can customize based on scenarios. In this example, the style panel requirements are:

  • You can select whether to display the legend

  • Can define start angle (number)

Analyzing the requirements shows that a checkbox and number editor needs to be defined. It is therefore defined, type: 'switch' and type: 'number' in the styleSchema. (See schema.type for currently supported editors.)

const componentMeta: Interfaces.ComponentMeta = {
  propsSchema: {
    styleSchema: {
      schema: {
        type: 'object',
        className: 'tabs-uischema-container',
        props: { mode: 'collapse' },
        properties: {
          // Enter the properties you want to customize here.
          display: {
            type: 'object',
            title: 'Display settings',
            properties: {
              showLegend: {
                type: 'switch',
                id: 'showLegend',
                defaultValue: true,
                props: {
                  mode: 'checkbox',
                  label: 'Show legends. ',
                },
              },
              startAngle: {
                title: 'Starting angle',
                id: 'startAngle',
                type: 'number',
                defaultValue: 0,
                props: {
                  placeholder: 'Output the starting angle',
                  maxLength: 140,
                },
              },
            },
          },
        },
      },
    },
  },
};

The two editors are automatically generated in the Style panel. The values entered by the editor can also be obtained in the customProps.viewConfig of the custom component.

Step 3: Develop an echarts chart

setOption(option) methods need to be called to develop charts. The following describes how to convert Quick BI passed-in properties into echarts received parameters.

  1. Create an echarts instance.

    Create a echarts instance in the mount method.

        // src/component.ts
      mount(props: Interfaces.LifecycleProps<Interfaces.ComponentProps>) {
        // ...
        this.chart = echarts.init(props.container as HTMLDivElement);
        this.setOption(props);
      }
  2. Convert data.

    Encapsulates a setOption method that is easily called during the mount and update phases.

    A customProps.data is a two-dimensional array that customProps.data[i] represents a row of data in a database table. Each row contains the values of the configured dimension and measure fields.

    customProps.data[i][j] represents the value of a cell in a database table. For more information about the data structure, see Custom Component API. fieldId is the ID of the dimension or measure field.

    Since the position of each row of data is fixed, to facilitate obtaining the value value through fieldId, you can create a map that maps fieldId and array subscripts.

    // src/component.ts
        setOption(props: Interfaces.LifecycleProps<Interfaces.ComponentProps>) {
        // The chart data.
        const data = props.customProps.data;
        // Specify the data panel format.
        const fieldSettingMap = props.customProps.viewConfig.fieldSettingMap;
        // The first row of data.
        const [firstRow] = data;
        // The position of each row of data is fixed. By establishing the mapping relationship between the array subscript and fieldId, it is convenient to use fieldId to obtain values.
        const fieldColumnIndexMap: {
          [key: string]: number;
        } = firstRow.reduce(
          (prev, curr, i: number) => ({
            ...prev,
            [curr.fieldId]: i,
          }),
          {},
        );
        }
  3. Set series.

    The series settings. You can obtain the dimensions and measures configured on the Data tab by using the customProps.dataConfig.

    // src/component.ts
        setOption(props: Interfaces.LifecycleProps<Interfaces.ComponentProps>) {
            // ... data
        // Filter all measures.
        const columnsFields = props.customProps.dataConfig.find(each => each.areaType === 'column')?.fields ?? [];
        // Specify the format of the data panel data.
        const fieldSettingMap = props.customProps.viewConfig.fieldSettingMap;
        // Convert the format.
        const series = columnsFields.map((each, i) => {
          const filedSetting = fieldSettingMap[each.fieldId];
          return {
            id: each.fieldId,
            type: 'bar',
            // The data value of each row based on the mapping between the fieldId and the subscript of the array.
            data: data.map(row => row[fieldColumnIndexMap[each.fieldId]]?.value),
              coordinateSystem: 'polar',
              // Set the alias.
              name: filedSetting?.aliasName ?? each.showName,
          };
        });
        // ...
        this.chart.setOption({
          series,
          // ...
        });
        }
  4. Set category.

    Set the category. Since the rounded corner ring chart only receives one dimension, the first dimension can be used.

    // src/component.ts
        setOption(props: Interfaces.LifecycleProps<Interfaces.ComponentProps>) {
        // Filter all measures.
        const rowFields = props.customProps.dataConfig.find(each => each.areaType === 'row')?.fields ?? [];
        // Only one dimension is limited in meta.
        const [onlyRow] = rowFields;
        const category = data.map(row => row[fieldColumnIndexMap[onlyRow?.fieldId]]?.value);
        // ...
        this.chart.setOption({
          radiusAxis: {
            type: 'category',
            data: category,
            z: 10,
          },
          // ...
        });
        }
  5. Read the Styles panel.

    The value of the form configured in the Style panel, which can be obtained by customProps.viewConfig. In this example, the form of the checkbox editor is named showLegend, and the form of the number input box is named startAngle, and they are all set under display, so you can obtain them through customProps.viewConfig.display?.showLegend.

    // src/component.ts
        setOption(props: Interfaces.LifecycleProps<Interfaces.ComponentProps>) {
        const showLegend = props.customProps.viewConfig.display?.showLegend;
            const startAngle = props.customProps.viewConfig.display?.startAngle;
        // Set echarts.
        this.chart.setOption({
          angleAxis: {
            startAngle,
          },
          legend: {
            show: viewConfig.display?.showLegend,
            data: legend,
            top: 10,
            padding: 0,
          },
          // ...
        });
        }
  6. Create drill-down, linkage, and jump effects.

    Quick BI provides the customProps.dispatch method. You can call this method to implement drill-down, linkage, and jump. Where dataIndex is the array index of the dimension to be present in the customProps.data.

    // component.ts
        const dispatch = props.customProps.dispatch;
        if (typeof dispatch === 'function') {
          // Drill-down, interaction, and jump events.
          echarts.on('click', (serie: any) => {
            dispatch({
              type: 'select',
              payload: {
                dataIndex: serie.dataIndex, // dataIndex is the array subscript of the clicked row in data.
              },
            });
          });
          // Click the blank space event, which is used to adapt to the drill-down of the mobile terminal.
          echarts.getZr().on('click', function (e) {
            if (!e.target) {
              dispatch({
                type: 'cancelSelect',
              });
            }
          });
        }

After completing the above steps, the chart can be displayed. The next step is to modify the style and adjust the data format. For more information, see the comments in Complete sample code.

Step 4: Package

After the development is complete, you need to package the custom component.

npm run pack

The output results are stored in the build directory. You can upload the output results to the custom component platform and publish the component.

imageFor more information, see Debug components in Quick BI dashboards.