What are the steps for generating a diagram using Chart.js?

I'm attempting to use Chart.js to create a specific diagram.

Current Challenges:

  • The point on the x-axis should be centered within the categories.
  • I would like the value to appear above the point.

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

This is what my code looks like so far:

new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Buy', 'Sell'],
        datasets: [
            ...grid.pairs.map(pair => {
                return {
                    data: [pair.buyPrice, pair.sellPrice],
                    borderColor: '#0d6efd',
                    backgroundColor: '#0d6efd',
                    pointRadius: [3, 5],
                }
            }),
            {
                label: 'Market Price',
                data: [grid.marketPrice, grid.marketPrice],
                borderColor: 'red',
                backgroundColor: 'red',
            }
        ]
    },
    options: {
        scales: {
            x: {
            },
            y: {
                title: {
                    display: true,
                    text: 'Price in Euro'
                },
            }
        },
    }
})

If anyone could offer some assistance with this, it would be greatly appreciated.

Answer №1

Switching to a bar chart places the data points at the center of each bar, which aligns with the request. Each individual data series is specified as type: 'line'

const ctx = document.getElementById('myChart');
const grid = {
  marketPrice: 12,
  pairs: [{
      buyPrice: 12,
      sellPrice: 3
    },
    {
      buyPrice: 16,
      sellPrice: 6
    },
    {
      buyPrice: 17,
      sellPrice: 2
    },

  ]

}
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Buy', 'Sell'],
    datasets: [
      ...grid.pairs.map((pair, index) => {
        return {
          label: 'Series ' + index,
          type: 'line',
          data: [pair.buyPrice, pair.sellPrice],
          borderColor: '#0d6efd',
          backgroundColor: '#0d6efd',
          pointRadius: [3, 5],
        }
      }),
      {
        type: 'line',
        label: 'Market Price',
        data: [grid.marketPrice, grid.marketPrice],
        borderColor: 'red',
        backgroundColor: 'red',
      }
    ]
  },
  options: {
    scales: {
      x: {},
      y: {
        title: {
          display: true,
          text: 'Price in Euro'
        },
      }
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js" integrity="sha512-ZwR1/gSZM3ai6vCdI+LVF1zSq/5HznD3ZSTk7kajkaj4D292NLuduDCO1c/NT8Id+jE58KYLKT7hXnbtryGmMg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div>
  <canvas id="myChart"></canvas>
</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

Acquiring the assigned class attribute

I have an image that triggers ajax requests when clicked. To pass a variable from $_GET[] to my onclick function, I came up with the following solution: <img id="img1" class="<?=$_GET['value']"?> /> and using jQue ...

Disable image loading for users who have javascript enabled

I find myself caught in a chicken-egg dilemma. The webpage I created contains numerous images that need to be loaded, and so I implemented a script that loads images as the user scrolls, similar to how Facebook or Google Images functions. When the user rea ...

Issue with setting GeoJSON in jQuery callback using Mapbox`

Using Jquery, I am trying to retrieve geojson points data (which will set markers on a map) from a database. function remm(id){ $.ajax({ type: "POST", url:"geojson2.php", data:{ u_id:id[0], t_id:id[2] }, success: functi ...

What is the most effective way to output data using the response.write method in a Node.js program after retrieving it from a MySQL server?

Currently working on a NodeJS web app and encountering a roadblock. Seeking feedback on my code: var config = require('./config.json'); var mysql = require('mysql'); var http = require('http'); var url = require('url&apo ...

ts-jest should replace the character '@' with the '/src' folder in the map configuration

I have set up a node project using TypeScript and configured various paths in my tsconfig.json file, such as: "paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl' ...

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

The art of rotating PDF files and various image formats

Looking for a way to rotate PDF and image files displayed on an HTML page using jQuery. I attempted: adding a CSS class - without success. Here is an example code snippet: .rotate90 { webkit-transform: rotate(90deg); moz-transform: rotate(90de ...

The files being requested by jQuery Slimbox are not being retrieved properly

I am currently utilizing jQuery slimbox along with its Application Programming Interface (API). Below is the JavaScript code snippet that retrieves image paths through JSON and then triggers the slimbox using its API. $('#main-container').appen ...

Upon upgrading to webpack 5.x, I encountered the error message `Error: getaddrinfo ENOTFOUND localhost:8081` when trying to run `npm run serve`. What could be causing

Recently, I was tasked with upgrading a Vue project from webpack 4.x to webpack 5.x. Prior to the upgrade, my vue.config.js file looked like this: devServer: { port: 8081, public: process.env.PUBLIC_ADDRESS, }, The variable PUBLIC_ADDRESS was defined ...

What steps can I take to resolve the CLIENT_MISSING_INTENTS issue?

After diving into learning about discord.js, I've run into a bit of a roadblock. Despite trying to troubleshoot by searching online, I can't seem to resolve the issue. const Discord = require('discord.js'); // const Discord = require(&a ...

Ajax: Why am I receiving an error response instead of a successful one?

It's puzzling why my code is triggering the error function instead of success. The console.log keeps showing me this: Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: f ...

Having difficulties accessing the git repository through the application

I am currently working on a Node.js application that needs to connect to a Git repository via the app. The connection works fine locally, and it also runs smoothly when I docker build and run it within a container on my local machine. However, upon deplo ...

Change not accepted

I am a beginner in Angular and still grappling with the fundamentals. On my menu, I have a cart icon with an initial value of 0 upon first load. In my product list, each product has an 'AddToCart' button. What I aim to achieve is- I want to dy ...

the sequence in which a node executes a javascript function

Trying to update req.session.cart with new values for prod.quantity and prod.qtyCount in the shoppingCart field of order.save(). The issue is that orders are being saved with default quantity and qtyCount values, even though I'm setting cartProducts[ ...

Creating a variety of Flexslider slideshows on the fly

Check out this snippet of code: <?php foreach ($objVideos as $objVideo) : ?> jQuery('#carousel-<?php echo $objVideo->id; ?>').flexslider({ animation: "slide", controlNav: false, animationLoop: false, ...

Unable to prolong TypeScript document

As I develop a drag and drop interface, upon dropping a file, the native File is retrieved. To enhance this interface with additional information, I decided to explore various approaches. In my initial attempt, I utilized: interface AcceptedFile extends ...

I require my two elements to possess opposing transformations in their coordinates or directions to enable dragging capabilities

Changing the code to move the elements in opposite directions is my goal. I attempted multiplying the second element by -1, but unfortunately, I keep ending up with a NAN or undefined result. Any suggestions on how to achieve the desired effect? ...

Using JavaScript Object Constructor to alter text color

Seeking some guidance as a newbie here on how to deal with a problem I'm currently tackling. I understand that using an object constructor may not be the most efficient way to handle this, but I'm eager to enhance my knowledge of objects. My quer ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...

What is the best way to verify async actions that update the UI in my React Native application?

Currently, my setup involves utilizing jest alongside @testing-library/react-native. Below is a snippet of code: Upon clicking a button, a function is dispatched: onPress(_, dispatch) { dispatch(getUserAddresses()); }, This dispatched functi ...