What is the method for inserting indicators between yAxis values in a yAxis ChartJs graph?

I have a line chart displaying the link below: https://i.sstatic.net/yUAHf.png

There is a noticeable gap between 0-0.7 on the chart. I am looking to add an indicator similar to the one shown in this image:

https://i.sstatic.net/pRjsY.png

The desired outcome would resemble this example: https://i.sstatic.net/IaqM5.png

When attempting to draw something on the ChartJs chart using annotations, I encountered difficulty setting intervals for drawing lines. Here's what I attempted:

   annotation: {
  annotations: [{
            drawTime: 'afterDraw', // overrides annotation.drawTime if set
            id: 'a-line-1', // optional
            type: 'line',
            mode: 'vertical',
            scaleID: 'y-axis-0',
    value: 0,
    borderColor: '#000',
            borderWidth: 2,
        }]
  }

Unfortunately, there are no accepted values like yMax and yMin when drawing lines, so I am unsure how to proceed. Any assistance with this issue would be greatly appreciated.

For reference, here is the Fiddle link: http://jsfiddle.net/3du6ya1c/

Answer №1

The Plugin Core API provides various hooks for executing custom code. One useful hook is the afterDraw hook, which allows you to draw an image directly on the canvas using CanvasRenderingContext2D.

plugins: [{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    var xAxis = chart.scales['x-axis-0'];
    var yAxis = chart.scales['y-axis-0'];
    var image = new Image();
    image.src = 'https://i.sstatic.net/zyhEv.png',
    ctx.drawImage(image, xAxis.left - 11, yAxis.bottom - 16, 20, 10);    
    ctx.restore();
  }
}],

Check out the following example code snippet to see how it can be implemented.

new Chart(document.getElementById("myChart"), {
  type: "line",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      var image = new Image();
      image.src = 'https://i.sstatic.net/zyhEv.png',
      ctx.drawImage(image, xAxis.left - 10, yAxis.bottom - 16, 20, 10);     
      ctx.restore();
    }
  }],
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "APAC RE index",
      data: [0.7, 0.8, 0.9, 1, 0.9, 0.8, 0.7],
      fill: false,
      borderColor: "rgb(255, 0, 0)"
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: 0.65,
          stepSize: 0.1,
          callback: (value, index, values) => index + 1 == values.length ? 0 : value
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

~

Answer №2

Consider utilizing box annotation and defining the y-axis and x-axis range for it.

annotation: {
      annotations: [{
        drawTime: 'afterDraw', // overrides annotation.drawTime if set
        id: 'a-line-1', // optional
        type: 'box',
        borderWidth: 10,
        borderColor: 'green',
        xScaleID: 'x-axis-0',
        yScaleID: 'y-axis-0',
        xMin: "January",
        xMax: "January",
        yMax: 0.7,
        yMin: 0.0,
      }]
    }

Take a look at this example in action.

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

What is the best approach to selectively insert a portion of a fully loaded page from $.ajax(), all while running embedded scripts?

Currently, I am utilizing the $.ajax() function to load new pages on my website under specific conditions (such as the presence of a flash-based radio player). However, I am looking for a solution that does not involve altering the server-side output in th ...

Error encountered: Circular reference issue was encountered when attempting to retrieve navigator.plugins with the use of Selenium and Python

I'm attempting to access the value of navigator.plugins from a Selenium-driven ChromeDriver initiated google-chrome Browsing Context. Using google-chrome-devtools, I am able to retrieve navigator.userAgent and navigator.plugins as shown below: https ...

Caution when using a React form: Value of `true` has been detected for a non-boolean attribute `validate`

I am trying to address a warning message that I have received index.js:1 Warning: Received true for a non-boolean attribute validate. If you want to write it to the DOM, pass a string instead: validate="true" or validate={value.toString()}. I ...

React - Dealing with rendering issue when toggling a button using LocalStorage and State

For quite some time now, I've been struggling with a particular issue... I'm encountering challenges in using the current state to display a toggle button that can both add and remove an item from local storage. The code below manages to add and ...

The header does not extend fully to the top edge

I am attempting to relocate the header to the topmost position on my webpage. However, despite my efforts, it remains in its current position. You can view an example of the issue in this fiddle http://jsfiddle.net/DCtH7/4/ Upon examining the fiddle, you ...

Make sure to wait for the complete loading of all content in the AJAX response before showing it on

I am currently working on a search function that sends a json request to the server for results every time a character is entered. Although this part is functioning correctly, I am trying to figure out how to add a loading class to .search-load > .conta ...

Incorporate a smooth transition effect to a dynamically resizing div button

In my current setup, I have 3 buttons that can toggle between different visible divs. In the future, I may add more buttons to switch between additional divs. At the moment, the first div is active (display set to block), while all other divs are hidden ( ...

Using Redux to Implement Conditional Headers in ReactJS

I am planning to develop a custom component named HeaderControl that can dynamically display different types of headers based on whether the user is logged in or not. This is my Header.jsx : import React from 'react'; import { connect } from &a ...

It is not possible to add items to an array

Attempting to retrieve data from the database using the callback method "getAllOrdersByUserId". The output is displayed below: [ TextRow { DishOrderId: 163, BagId: 'BPZDXT68148', DateCreated: 2021-05-27T03:55:05.000Z, Bags: & ...

Ways to retrieve child state in React?

After creating my own form component with a render() method that looks like this: render() { return ( <form onSubmit={this.onSubmit} ref={(c)=>this._form=c}> {this.props.children} </form> ) } I enabled ...

Numerous websites with scroll-based navigation

I am currently building a unique website that includes scrolling in various directions without the use of a horizontal scrollbar. The design is similar to this image: https://i.stack.imgur.com/Ex2Bf.jpg. It is a one-page website where vertical scrolling ...

Prevent any clicking on the page for a brief period of time following the execution of a function

After clicking a div, an image appears and the user can click the image to hide it. To prevent the user from accidentally closing the image while waiting for it to appear, I want to disable all clicks on the page for a few seconds after the div is clicked. ...

retrieve the current page/url using an attribute selector

I've been attempting to format a text menu in my CSS so that the link matches the current URL, but it doesn't appear to be working. Here's the code snippet: #pages.tabs ul li a[href$=location]{color:blue !important;} , where #pages.tabs ul ...

The appearance of the mock button varies between the development and production environments due to CSS styling

I'm currently using CSS to style a hyperlink in order to give it the appearance of a button. This is for a .NET website. a.pretend { display:inline-block; border-top:1px solid #CCCCCC; border-left:1px solid #CCCCCC; border-bottom:1px solid #999999; b ...

Manage Camera Movement for 360-Degree Image Viewing in A-Frame

I'm struggling to find any guidance on how to control Camera Rotation in A-Frame. I have a 360 image set up as the <a-image> element. I want the image or camera to rotate as I move the mouse over the screen - moving the mouse right should move t ...

Having trouble with VueJS method not getting called after an asynchronous function callback?

I'm currently utilizing VueJS along with Stripe to create a form that can be submitted without needing to refresh the page. While the Stripe functionality is operational, the issue I'm facing doesn't seem to be directly related to Stripe. T ...

Firefox detects video interference from webcam

Take a look at this test code: <!doctype html> <html> <body> <video id="v1" autoplay="autoplay"></video> <script> navigator._getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserM ...

What is the best way to preserve an apostrophe within a variable in JavaScript without it being replaced?

How can I send the value of NewText in its original form from .cs code using an ajax call? **var NewText ="D'souza";** $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: " ...

Printing content using JavaScript on a point of sale (POS) printer with

I need to print a specific div on my POS printer named Optimuz. I have attempted using the following code: <div id="printAreaInvoice" style="visibility: hidden;font-size:8px;width:200px;"></div> < ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...