Echarts Bar horizontal bar chart example code

Echarts Bar horizontal bar chart example code

Continuing from the previous article # Echart Bar histogram style detailed explanation, you can read the previous article first, if you don’t read it, the impact is not particularly large.

Horizontal bar chart

Dynamically update data and styles

Realize dynamic switching between monthly statistics and daily statistics. When statistics are calculated by month, data for each month will be displayed, and the x-axis will show 12 labels; when statistics are calculated by day, the x-axis will not fully display all labels, but will display them at intervals, and the width of the column will also change. The main method used is the setOption method.

Official documentation [setOption]: echarts.apache.org/zh/api.html…

<script>
  import * as R from "ramda";

  const source1 = [
    ["January", 1330, 666, 560],
    ["February", 820, 760, 660],
    ......
    ["November", 901, 880, 360],
    ["December", 934, 600, 700],
  ];
  const source2 = [
    ["1 day", 1330, 666, 560],
    ["2nd", 820, 760, 660],
    ......
    ["29th", 934, 600, 700],
    ["30th", 1330, 666, 560],
  ];

  // The specific configuration is as shown before, the details are omitted, only the basic example is shown const initOption = {
    ...
    dataset: { source: source1 },
  };

  export default {
    data() {
      return {
        charts: null,
        isDaily: false,
      };
    },
    mounted() {
      this.charts = this.$echarts.init(
        document.getElementById("barCharts"),
        null,
        {
          renderer: "svg",
        }
      );
      this.charts.setOption(R.clone(initOption));
    },
    methods: {
      handleSource() {
        this.isDaily = !this.isDaily;
        this.charts.setOption(
          R.mergeDeepRight(initOption, {
            // Dynamically update data source dataset: {
              source: this.isDaily ? source2 : source1,
            },
            xAxis:
              // Dynamically update label interval axisLabel: {
                interval: this.isDaily ? 4 : "auto",
              },
            },
            series: R.map(
              // Dynamically update the column width (o) => ((o.barWidth = this.isDaily ? 12 : 24), o),
              initOption.series
            ),
          }),
          true
        );
        this.charts.resize();
      },
    },
  };
</script>

Solve the problem of echarts width and height adaptation

When making charts in web projects, the width and height of the chart are not fixed and need to adapt to the width and height of the browser. The method used is resize. If there are multiple charts, they need to be resized simultaneously.

<script>
  export default {
    mounted() {
      window.addEventListener("resize", this.handleResize, false);
    },
    destroyed() {
      window.removeEventListener("resize", this.handleResize);
    },
    methods: {
      handleResize() {
        const _this = this;
        const timer = setTimeout(() => {
          _this.lineCharts.resize();
          _this.barCharts.resize();
        }, 500);
        // Clear the timer this.$once("hook:beforeDestroy", () => {
          setTimeout(timer);
        });
      },
    },
  };
</script>

Vertical bar chart

Vertical bar chart implementation

The essence is the same as the horizontal direction, just replace the x and y axis values; the x axis is value, and the y axis is category

let option = {
  xAxis:
    type: "value",
  },
  yAxis: {
    type: "category",
  },
};

Coordinate indicator background gradient color

In fact, the principle is the same as the horizontal one, that is, the x and y values ​​of the gradient color processing area are changed.

let horizontalColor = {
  type: "linear",
  x: 1, // Change y: 0,
  x2: 0,
  y2: 0, // Change colorStops: [
    { offset: 0, color: "rgba(234,244,255,1)" },
    { offset: 1, color: "rgba(234,244,255,0.3)" },
  ],
  global: false,
};

Columns set different colors

The color in the series property setting of the column can be a function and processed in the function. The core code is colorList[params.dataIndex]

let colorList = [
  "#1890ff",
  "#52c41a",
  "#faad14",
  "#f5222d",
  "#1DA57A",
  "#d9d9d9",
];
let series = [
  {
    type: "bar",
    barWidth: 16,
    itemStyle: {
      // Customized display (in order) to achieve different color columns color: (params) => {
        return colorList[params.dataIndex];
      },
    },
    dimensions: ["Type", "Sales Quantity"],
  },
];

Display values ​​above the bar graph

The label in the series property setting of the column can be a function and processed in the function. You can set the position, font color and size, etc. The core code is params.value[params.encode.x[0]].

let series = [
  {
    // ......
    type: "bar",
    label: {
      // Column chart header display value show: true,
      position: "right",
      color: "#333",
      fontSize: "12px",
      formatter: (params) => {
        return params.value[params.encode.x[0]];
      },
    },
  },
];

Tooltip prompt box customization

Same as horizontal, just pay attention to the values ​​params[0].axisValue, item.seriesName, item.value[item.encode.x[0]]

let tooltip = R.merge(tooltip, {
  formatter: function(params) {
    let html = `<div style="height:auto;width:163px;">
          <div style="font-size:14px;font-weight:bold;color:#333;margin-bottom:16px;line-height:1;">
            ${params[0].axisValue}
          </div>
          ${params
            .map(
              (
                item
              ) => `<div style="font-size:12px;color:#808080;margin-bottom:8px;display:flex;align-items:center;line-height:1;">
                <span style="display:inline-block;margin-right:8px;border-radius:6px;width:6px;height:6px;background-color:${
                  item.color
                };"></span>
                ${item.seriesName}
                <span style="flex:1;text-align:right;">${
                  item.value[item.encode.x[0]]
                }</span>
              </div>`
            )
            .join("")}
        </div>`;
    return html;
  },
});

Overall Implementation

charts.setOption({
  title:
    text: "Sales Quantity Distribution",
  },
  dataset:
    source: [
      ["Apple", 200],
      ["Peach", 180],
      ["Grapes", 340],
      ["Banana", 250],
      ["Mango", 166],
      ["Durian", 185],
    ],
  },
  xAxis: R.merge(yAxis, {
    type: "value",
  }),
  yAxis: R.mergeDeepRight(xAxis, {
    type: "category",
    axisPointer:
      shadowStyle: {
        color: horizontalColor,
      },
    },
  }),
  series,
  tooltip,
});

Summarize

This is the end of this article about Echarts Bar horizontal bar chart. For more relevant Echarts Bar horizontal bar chart content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Gradient color bar chart implemented by jQuery plugin Echarts
  • Example of multi-column bar chart effect implemented by jQuery plugin echarts [with demo source code download]
  • Solve the problem that echarts shows two values ​​in a bar chart, similar to a progress bar
  • echarts bar chart background overlapping combination instead of parallel implementation code
  • Echarts Basic Introduction: General Configuration of Bar Chart and Line Chart

<<:  Solution to the MySQL server has gone away error

>>:  MySQL master-slave data is inconsistent, prompt: Slave_SQL_Running: No solution

Recommend

The whole process of implementing the summary pop-up window with Vue+Element UI

Scenario: An inspection document has n inspection...

mysql solves the problem of finding records where two or more fields are NULL

Core code /*-------------------------------- Find...

【HTML element】How to embed images

The img element allows us to embed images in HTML...

MySQL binlog opening steps

Binlog is a binary log file that is used to recor...

JavaScript implements fireworks effects with sound effects

It took me half an hour to write the code, and th...

Detailed explanation of Vue advanced construction properties

Table of contents 1. Directive custom directive 2...

Example code for implementing raindrop animation effect with CSS

Glass Windows What we are going to achieve today ...

Detailed explanation of webpack-dev-server core concepts and cases

webpack-dev-server core concepts Webpack's Co...

How to use Maxwell to synchronize MySQL data in real time

Table of contents About Maxwell Configuration and...

Sample code for nginx to achieve dynamic and static separation

1. Simple configuration of nginx's dynamic an...

How to build a tomcat image based on Dockerfile

Dockerfile is a file used to build a docker image...

A general method for implementing infinite text carousel with native CSS

Text carousels are very common in our daily life....

Installing Windows Server 2008 operating system on a virtual machine

This article introduces the installation of Windo...