Horizontal line chart in Chart.js or a customized version of the horizontal bar chart

I'm currently using chart.js to create a timeline showcasing events in relation to the current date.

While the horizontal bar chart is useful, I would prefer displaying only the tips of the bars as points essentially transforming it into a horizontal line chart.

I've included my horizontal bar chart as well as a mock-up demonstrating what it could look like as a horizontal line chart.

Could this be achieved with chart.js?

https://i.stack.imgur.com/6mWpD.png

Answer №1

It is important to understand that all the editable information about a chart is stored in the variable that holds the chart data (myChart customarily, or my2Bar as shown in this fiddle).

If you wish to make global changes to the graph, you will need to modify attributes within myChart.config.options.
For specific chart modifications, adjust attributes located in myChart.config.data.

In this instance, you are required to alter a specific chart, namely the horizontal bar.


Upon examining your graph logs and delving deep into the config, you will discover that the bars in your chart are created using elements saved in
myChart.config.data.datasets[0]._meta[0].data[n]._model
(n representing the order of rectangles drawn from top to bottom).

Some attributes found here include:

  • base : The starting X position where the rectangle is drawn (e.g., 0 on your x-axis).
  • x : The final X position where the rectangle ends.
  • height : The height of the rectangle.
  • and more ...

To adjust these values, iterate through the various rectangles (represented by n in the path above).

However, manual adjustments directly in your variable's config won't suffice due to chart responsiveness (redrawing with previous settings upon resizing).


The solution lies in utilizing Chart.js plugins.

Plugins enable you to manage events occurring during graph creation, updating, and rendering.

Within the beforeRender event (initiated after setup but before drawing), iterate over the rectangles to edit values affecting their appearance:

beforeRender: function(chart) {
    for (var i = 0; i < chart.config.data.datasets[0]._meta[0].data.length; i++) {
        // Adjust both `3` values to change point height & width 
        chart.config.data.datasets[0]._meta[0].data[i]._model["base"] = chart.config.data.datasets[0]._meta[0].data[i]._model["x"] + 3;
        chart.config.data.datasets[0]._meta[0].data[i]._model["height"] = 3;
    }
}

Here is the jsFiddle link showcasing the end result.
Note: I was unable to achieve rounded dots instead of squares.

https://i.stack.imgur.com/mZ4YT.png


Update :

I have also created another jsFiddle demonstrating all dots linked together, resembling a horizontal line chart (subject to enhancement, yet a solid beginning).

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 right rendering strategy to use for shouldComponentUpdate in React?

Provide an exhaustive list of all props required for rendering shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; ...

Exploring the World of Micro-Frontends with the Angular Framework

I am conducting research on the best methods for transitioning a large single-page application into a micro-frontend architecture. The concept: The page is made up of multiple components that function independently Each component is overseen by its own ...

Leveraging the power of the Twitter API to integrate real-time tweets into custom code

Looking for an API that can transform a tweet from Twitter into a string format suitable for integration into a program or website. Any recommendations? ...

The spring submission function requires the use of two parameters

As a beginner in spring web applications, I am facing an issue where the request mapping receives a "dual" parameter when I submit a form. The form structure is as follows: <form action="" method="post" name="myform"> ...... </form> To submit ...

Utilizing jQuery for AJAX-Based Deletion of Records

Hey, I stumbled upon a code snippet that allows me to delete a row from my database using Ajax. However, there seems to be an issue where the table that should disappear when deleted is not working properly. Here is the JavaScript code: <script type=" ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

Error: Discord.js was unable to access the 'id' property because it was undefined

I need help with my ticket system project where I am trying to create a channel and send an embed in that channel. However, when I run the code, I encounter the error message TypeError Cannot read property 'id' of undefined. Here is the snippet ...

Are there any libraries available that can assist with managing forms similar to how Google Contacts handles them

By default, Google Contacts has a feature where the form displays values with some of them being read only. However, when you click on a value, it converts the field into an editable form so you can easily make changes. After editing and pressing enter, th ...

Pattern matching for ' ... '

I've been struggling to make a regular expression work properly: I need it to match anything that starts with __(' or __(" and ends with ') or ") I attempted using /__\(['"][^']*['"]\)/g and /__\([&apos ...

Running JavaScript code on a webpage using Selenium

I'm currently developing an automated script to enter a person's address details on a webpage. It's important to note that I did not create this webpage myself. While filling in the address details, I encountered an option to select the coun ...

Unable to locate the root element for mounting the component in Cypress with React

I am currently testing my react app, which was created using create-react-app, with the help of cypress. Unfortunately, I encountered an error that looks like this: https://i.stack.imgur.com/xlwbo.png The error seems to be related to trying to fetch an ...

ADVENTURE BLOCKED - Intercept error: net::ERR_BLOCKED_BY_CLIENT

I've encountered an issue where my initialize function doesn't run properly when a user has an ad blocker enabled. It seems that the ads-script.js file is being blocked by the client with a net::ERR_BLOCKED_BY_CLIENT error, leading to my .done ca ...

Tips for preventing HTML ID clashes while integrating with the Document Object Model of external websites

When incorporating additional HTML elements into a webpage using Javascript or jQuery, along with external CSS declarations, it is important to avoid conflicts with existing IDs and class names already present on the page. This could lead to issues if ther ...

Inserting a variable into a JSON string

Within my code, I have a basic variable containing strings that are converted into a JSON object. My goal is to create an input field where a person's name can be entered and added to the text. The current setup looks like this var text = '{"st ...

The Angular method for retrieving the child's ID when it is clicked

As a newcomer to Angular 1.0 with a background in jQuery, I am facing the following scenario: Let's imagine we have the following HTML structure : <div id="filters"> <div id="filter1">Filter 1</div> <div id="filter2"> ...

Missing information in input field using JQUERY

I've been attempting to extract a value from an input tag, but all I keep getting is an empty string. Upon inspecting the frame source, it appears as follows: <input type="hidden" name="" class="code_item" value="00-00000159" /> In order to re ...

Determine the presence of a value within an array in mongodb

How can I determine if the current Meteor.user()._id exists in the "favoritedBy" array? If true, display "Your favorite", if false, display "Not your favorite". Here is an example document in MongoDB: { "_id" : "W5WwAZatorDEb6DNP", "createdBy" : "aT ...

Django: Is there a way to modify the PayPal script for pay upon arrival?

I currently do not wish to accept online payments on my e-commerce site. Instead, I would like the courier to handle package delivery and collection of fees. How can I modify the PayPal script to bypass validations and only register payments upon arrival? ...

A pop-up window for selecting a file within an <a> tag

Is there a way to create an Open File dialog box on a link within my webpage? I attempted <input name="uploadedfile" type="file"> However, it only functions as a button and does not allow for the selection of multiple files. I would like somethin ...

Error message displayed for invalid date format in Material UI (dateTime picker) after form submission

I recently integrated the Material Ui DateTime picker into my form. However, upon submitting the form, I encountered the following error: Invalid Date Format Image In my React app, I am utilizing JSON Server to store data. Displayed below is the outpu ...