Can anyone suggest a method to display a line above every individual bar on a bar chart?

I have a bar Chart and I am looking for a way to display a horizontal line above the bar to show the peak value. Is there any method within echarts that can achieve this without needing a custom renderer?

var myChart = echarts.init(document.getElementById('main'));

option = {
"series": [
    {
        "type": "bar",
        "dimensions": [
            "date",
            "percent",
            "tooltip"
        ],
        "color": "#1976d2",
        "data": [
            [
                "2023-01-11",
                3.230555555555555,
                "3.2"
            ],
            [
                "2023-01-12",
                5.436111111111111,
                "5.4"
            ],
            [
                "2023-01-13",
                7.306481481481481,
                "7.3"
            ],
        ],
        "name": "Mean",
    },
    {
        "type": "custom",
        "dimensions": [
            "date",
            "peak",
            "tooltip"
        ],
        "color": "#d32f2f",
        "renderItem": renderPeakLine,
        "data": [
            [
                "2023-01-11",
                25,
                25
            ],
            [
                "2023-01-12",
                50,
                50
            ],
            [
                "2023-01-13",
                50,
                50
            ],
        ],
        "yAxisIndex": 0,
        "name": "Peak",
    }
],
"xAxis": {
    "show": true,
    "type": "time",
    "axisLabel": {}
},
"yAxis": {
    "show": true,
    "type": "value",
    "min": 0,
    "max": 100,
    "scale": false,
},
"tooltip": {
    "show": true,
    "trigger": "axis",
    "axisPointer": {
        "label": {}
    }
},
"legend": {
    "show": true
}
}

const peakColor = '#d32f2f'

function renderPeakLine(param, api) {
const bandWidth = (param.coordSys.width / param.dataInsideLength) * 0.6
const point = api.coord([api.value(0), api.value(1)])

const value = api.value(2)

// This skips drawing the red line for 0
if (value === 0) return

return {
    type: 'line',
    transition: 'shape',
    z2: 10,
    shape: {
        x1: point[0] - bandWidth / 2,
        x2: point[0] + bandWidth / 2,
        y1: point[1],
        y2: point[1],
    },
    style: api.style({
        fill: null,
        stroke: api.visual('color'),
        lineWidth: 2,
    }),
}
}


myChart.setOption(option);
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.0.4/echarts.min.js"></script>

<div id="main" style="width: 500px;height:200px;"></div>

Answer №1

It seems like the chart type you are referring to is known as a candlestick chart.

var myChart = echarts.init(document.getElementById('main'));

option = {
  xAxis: {
    data: ["2023-01-11", "2023-01-12", "2023-01-13"]
  },
  yAxis: {
    show: true,
    type: "value",
    min: 0,
    max: 100,
    scale: false,
},
  series: [
    {
      type: 'candlestick',
      data: [
        [
          0,
          3.230555555555555,
          0,
          25
        ],
        [
          0,
          5.436111111111111,
          0,
          50
        ],
        [
          0,
          7.306481481481481,
          0,
          50
        ],
      ],
    }
  ]
};


myChart.setOption(option);
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.0.4/echarts.min.js"></script>

<div id="main" style="width: 500px;height:200px;"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for Creating JavaScript Code for HTML Helpers in ASP.NET MVC

My HTML helper includes a textBox that looks like this: @Html.TextBox("txt1") <br /> I am interested in triggering a javascript onchange event on this textbox. Can this be accomplished, or would it be better to use an HTML input type instead? ...

Exploring the impact of JavaScript tags on website performance in accordance with W3

While researching website optimization strategies today, I came across an article discussing the benefits of moving JavaScript scripts to the bottom of the HTML page. I am curious if this approach aligns with W3C's recommendations since traditionally ...

What methods can be used to prevent the appearance of the ActiveX warning in IE7 and IE8 when dealing with drop

I have a dilemma with my website where I am using JavaScript to modify CSS on hover for specific items. Interestingly, in Firefox everything runs smoothly without any ActiveX message popping up. However, in IE8, I encounter a warning stating "To help prote ...

Cookie setting issue in Next.js/React: The frustration continues

I'm currently attempting to retrieve a cookie in Next.js using Express, but while the backend functions correctly with Postman and retrieves the cookie token, the frontend is unable to obtain the cookie. Below is my backend code: const express = requi ...

Executing a Javascript Function within AngularJS

I encountered an issue where the error myFunction() IS NOT DEFINED is appearing: app.controller('myctrl',function(){ myFunction(); }); function myFunction() { debugger; document.getElementById("abc").disabled = false; } In this sce ...

"Enhance Your Website with a Sticky Bootstrap Navbar and Seamless Scroll Design - Elevating Padding and Margin-

I am currently working on incorporating a bootstrap sticky navbar with a fixed height of 81px and smooth-scroll behavior into my project. The website's HTML structure includes section tags like <section class="section" id="news" ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

Ensure that you select the checkbox if it is visible; if it is not, then you should

I am currently working on a page script and I only require a simple JavaScript solution. When a specific text, for example - no found, appears on the page, the script should automatically click the find work button. This action needs to be triggered at 1 ...

Observing data within an AngularJS service

I am currently working with a service called sharedData and a controller named HostController. My goal is to have the HostController monitor the saveDataObj variable within the sharedData service, and then update the value of host.dataOut, which will be re ...

Utilizing Jquery's .GET method to retrieve and handle JSON data

In the jQuery snippet below, I am trying to fetch product data from . However, I am facing difficulty in iterating through the loop to access all 30 products along with their details. $.get("https://dummyjson.com/products/1") .done(function ...

Executing a function after a return statement in Vue JS

I have a function that allows me to delete an account by calling the deleteAccount function. After successfully deleting the account, I would like the user to be automatically logged out from the vuex store. Although I currently use setTimeout as a workaro ...

Encountered a SyntaxError in vue + webpack regarding an invalid range in character class

I am currently using webpack 4.29.3 and vue.js 2.6.3 to create a simple hello world project. I expected the index.html file to render correctly, but I encountered an error: SyntaxError: invalid range in character class. This error is confusing because I&ap ...

Using the `preventDefault` method within an `onclick` function nested inside another `onclick

I am currently working on an example in react.js <Card onClick="(e)=>{e.preventDefault(); goPage()}"> <Card.body> <Media> <img width={64} height={64} className="mr-3" ...

The function is not being invoked, utilizing jQuery's .delegate method

Utilizing jquery delegate to call a function is effective. For example: $("body").delegate("div", "mouseover", function(){ alert("it works"); }); It also makes sense to reuse the same function in multiple places. Instead of duplicating the code, you can ...

Something seems off with the way WebGL is rendering shapes

I am encountering an issue with my code that is supposed to display parsed radar data on a Mapbox GL JS map using WebGL. While I have successfully managed to render the general radar shape on the map, the rendering is incorrect. Instead of drawing rectangl ...

Ways to validate code that relies on browser APIs

I am currently utilizing Node to run my unit-tests. There is a JavaScript module that I need to test in the browser. My code is considered "isomorphic", meaning it does not use language features that are unavailable in Node, such as exports. However, it ...

Is there a more efficient method for replacing all attributes on cloned elements?

While this code does the job, I can't help but feel like it's a bit outdated. I'm not very experienced with JS/JQuery and only use them when necessary. My approach involves cloning an element and then replacing all of its attributes with on ...

How to efficiently store and manage a many-to-many relationship in PostgreSQL with TypeORM

I have a products entity defined as follows: @Entity('products') export class productsEntity extends BaseEntity{ @PrimaryGeneratedColumn() id: number; //..columns @ManyToMany( type => Categories, categoryEntity => cat ...

Unable to retrieve module from directive template in Angular

I am currently working on creating a wrapper component for ngAudio. This wrapper will act as the player with controls and will interact with ngAudio's functions. However, I am facing some scope issues with it. I can inject ngAudio into the component&a ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...