Chart.js module for creating matrix charts

Overview

chartjs-chart-matrix

Chart.js v3.0.0 module for creating matrix charts

npm release npm bundle size GitHub Quality Gate Status documentation

Example

Matrix Example Image

Documentation

You can find documentation for chartjs-chart-treemap at https://chartjs-chart-matrix.pages.dev/.

Quickstart

">
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]">script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]">script>
head>
<body>
  <div class="chart-container">
    <canvas id="matrix-chart">
  div>
  <script>
    const chart = new Chart('matrix-chart', {
      type: 'matrix',
      data: {
        datasets: [{
          label: 'Basic matrix',
          data: [{x: 1, y: 1}, {x: 2, y: 1}, {x: 1, y: 2}, {x: 2, y: 2}],
          borderWidth: 1,
          borderColor: 'rgba(0,0,0,0.5)',
          backgroundColor: 'rgba(200,200,0,0.3)',
          width: ({chart}) => (chart.chartArea || {}).width / 2 - 1,
          height: ({chart}) => (chart.chartArea || {}).height / 2 - 1,
        }],
      },
      options: {
        scales: {
          x: {
            display: false,
            min: 0.5,
            max: 2.5,
            offset: false
          },
          y: {
            display: false,
            min: 0.5,
            max: 2.5
          }
        }
      }
    });
  script>
body>

This simple example is also available online in the documentation: https://chartjs-chart-matrix.pages.dev/usage.html

Development

You first need to install node dependencies (requires Node.js):

> npm install

The following commands will then be available from the repository root:

> npm run build        // build dist files
> npm test             // run all tests
> npm run lint         // perform code linting
> npm package          // create an archive with dist files and samples

License

chartjs-chart-matrix is available under the MIT license.

Comments
  • Matrix chart y axis labels (tick label) getting cut off and overlaps scale title

    Matrix chart y axis labels (tick label) getting cut off and overlaps scale title

    Y-axis tick labels are getting cut off much sooner when compared to other chartjs charts. For example, with a bar chart, I can have much longer labels before they start overlapping scale title or overflow the canvas: image A matrix chart containing the same data (labels) on the y-axis will overflow: image I have noticed while resizing, the bar chart will hold the y-axis in place while the rest of the chart resizes until a certain point. However, this is not the case for the matrix chart, resizing moves the y-axis no matter the available space. If I apply padding to the left of the chart it will allow me to see more of the labels but it also pushes the scale label right. This is probably chartjs behavior, and applying negative padding to the scale label will negate all the padding): image Is there something I am missing?

    opened by syeanot 18
  • Trouble running under React

    Trouble running under React

    Hi! I've got an example that runs well using your Matrix Chart on Categories example within an HTML file which loads JS files using your Util function. No problem. But when I try to reproduce the exact same chart in a React context, I run into two issues:

    1. If I use plain npm install chartjs-chart-matrix I get v0.1.3 and chart.js 2.9.4 as the loaded dependency. The chart loads without a type error (i.e. the matrix type appears to have been added), but I just get an empty graph that seems to completely ignore the data and scales. Just a blank graph with axes going from 0 to 1.

    2. Finding the same issue with the HTML example and older chartjs-chart-matrix/chart.js versions, I became convinced that I should use chartjs-chart-matrix 1.0.0-beta, which loads chart.js 3.0.0-beta7 as a dependency. But when I try those versions, React throws the following error:

    TypeError: chart_js__WEBPACK_IMPORTED_MODULE_1__.default is not a constructor
    

    which appears to be thrown by the constructor in

        componentDidMount() {
            const { chartData, samples, features, dataOptions } = this.props;
            this.chart = new Chart(this.graph, { ....
    

    Do you have an example of current chartjs-chart-matrix usage in a React app? I've got a situation where I have to load code and modules via React, I do not have access to the containing HTML, which is outside of the project. Thanks!

    By the way, I'm importing chartjs-chart-matrix with the following:

    import React from 'react';
    import Chart from 'chart.js';
    import 'chartjs-chart-matrix'
    
    opened by sammyjava 10
  • Scale Ticks do not update when data is updated (filtered)

    Scale Ticks do not update when data is updated (filtered)

    Hi, in a normal JSChart the scale ticks also update when the underlying data is updated.

    E.g. there is on x-axis the ticks {a,b,c} and data for all of them. After filtering there is no more data for 'b'. While the matrix-tile disappears the 'b'-tick still stays in place. In normal ChartJS 'b' would also disappear now. In Matrix it doesnt.

    In Pictures: How it looks at the beginning: image

    How it should look after filtering data (in this case no more data for [B,Z]): image

    How it actually looks: image

    I tried several play arounds with the labels-array of a dataset' but it seems that chartjs-matrix is ignoring this array. Instead I was able to achieve tiny changes when working on scales/x/labels. When using an empty array [] the chartjs-matrix gathers the labels on its own by the given intial data (in this sample this is {a,b,c}). This does not change after updating the data. When using a non-empty array ['a','b','c']} this leads to the same behavior.

    scales: { x: { title: { display: true, text: 'Grade' }, position: 'top', type: 'category', labels: ['d','e','f'], ticks: { display: true }, grid: { display: false } },

    I tried overwriting any array in the dataset or the chart, but did not have luck yet. There are severy places knowing of scale-ticks possibly reliable. A short print-out: image

    Any ideas?

    opened by Kaspatoo 9
  • Adding Matrix Chart to Angular

    Adding Matrix Chart to Angular

    I know this is very similar to issue #7, but I am still unable to add the Matrix chart type to my angular project after reading through issue #7 as well as other resources online.

    I am using ng2-charts package and have added chart.js to the project as well. I tried to create a new chart component

    import { Component, Input, OnInit } from '@angular/core';
    import { Chart, ChartDataSets, ChartOptions, ChartType } from 'chart.js';
    import { Controller } from 'chartjs-chart-matrix';
    
    @Component({
      selector: 'comp-chart',
      templateUrl: './chart.component.html',
      styleUrls: ['./chart.component.scss'],
    })
    
    export class ChartComponent implements OnInit {
    
      @Input() chart: {
        type: ChartType,
        datasets: ChartDataSets,
        options: ChartOptions
      };
    
      constructor() {
        Chart.controllers.matrix = Controller;
      }
    }
    

    Here is the HTML code

    <div>
      <canvas baseChart *ngIf="chart" [datasets]="chart.datasets" [options]="chart.options" [chartType]="chart.type"></canvas>
    </div>
    

    When I run the code, I am getting an error stating the matrix type is unsupported.

    ERROR Error: getColors - Unsupported chart type matrix
        at getColors (ng2-charts.js:57)
        at ng2-charts.js:520
        at Array.forEach (<anonymous>)
        at BaseChartDirective.updateColors (ng2-charts.js:510)
        at BaseChartDirective.propagateDatasetsToData (ng2-charts.js:761)
        at BaseChartDirective.ngOnChanges (ng2-charts.js:545)
        at BaseChartDirective.wrapOnChangesHook_inPreviousChangesStorage (core.js:26979)
        at callHook (core.js:4730)
        at callHooks (core.js:4690)
        at executeInitAndCheckHooks (core.js:4630)
    

    Your assistance is deeply appreciated.

    opened by gastroguy 9
  • Fix MatrixDataPoint types

    Fix MatrixDataPoint types

    Based on the chartjs-chart-matrix examples, there should be v and optional d properties in the MatrixDataPoint type. Also, x and y can be of string type.

    opened by evenfrost 8
  • Type definitions

    Type definitions

    Hello,

    I would like to use this extension in a typescript react app with react-chartjs-2, but looks like the compiler missing the type definitions:

    import { MatrixController, MatrixElement } from 'chartjs-chart-matrix';
    
    Could not find a declaration file for module 'chartjs-chart-matrix'. 'D:/NodeJS/.../node_modules/chartjs-chart-matrix/dist/chartjs-chart-matrix.js' implicitly has an 'any' type.
      Try `npm i --save-dev @types/chartjs-chart-matrix` if it exists or add a new declaration (.d.ts) file containing `declare module 'chartjs-chart-matrix';
    
    bug 
    opened by teddybee 5
  • Multi type charts (Chart.js)

    Multi type charts (Chart.js)

    Does anyone have an example of mixing 2 charts, 1 of them a matrix one. I have an implementation but the charts have different dimmensions and do not merge together as supposed.

    What I want i something like the category scale example with an addition of a scatter/bubble chart on top.

    Is it possible? Screen Shot 2022-01-17 at 10 01 47

    opened by rferreira98 4
  • Is 'scales: never' in type definition correct?

    Is 'scales: never' in type definition correct?

    Currently the following declaration exists:

    declare module 'chart.js' {
      export interface ChartTypeRegistry {
        matrix: {
          chartOptions: CoreChartOptions<'matrix'>;
          datasetOptions: MatrixControllerDatasetOptions<'matrix'>;
          defaultDataPoint: MatrixDataPoint;
          parsedDataType: MatrixDataPoint;
          metaExtensions: AnyObject;
          scales: never;
        }
      }
    }
    

    Is it correct that scales has type never (https://github.com/kurkle/chartjs-chart-matrix/blob/next/types/index.esm.d.ts#L36)?

    Looking at the examples, setting scales should be possible (https://github.com/kurkle/chartjs-chart-matrix/blob/next/docs/samples/basic.md?plain=1#L56). In my case, this was resulting in the following error:

      Types of property 'scales' are incompatible.
        Type '{ y: { type: string; offset: boolean; grid: { display: boolean; }; }; x: { type: string; offset: boolean; labels: string[]; grid: { display: boolean; }; }; }' is not assignable to type '_DeepPartialObject<{ [key: string]: never; }>'.
    

    Changing:

    scales: never;
    

    to

    scales: { [key: string]: Scale };
    

    solved my issue. Note that Scale is provided by chart.js.

    bug types 
    opened by brocaar 4
  • Calendar Matrix issue

    Calendar Matrix issue

    Hello, thanks for the nice plugin!

    Background

    I am trying to create a calendar matrix, similar to one of the samples in this Repository. This is the example I've created. https://codepen.io/darkysharky/pen/qBqvGEy?editors=0010

    Issue

    What I need is day names on the y axis, and weeks on the X axis. Everything seems to work properly, but the only issue I stumble upon is the y axis names. As you can see, some are duplicated, some are missing and the order is not kept at all. Basically, I want to have the days from Monday to Sunday on the left and the weeks on the bottom, so I can quickly see at what day and what week something has occurred.

    question 
    opened by angelnikolov 4
  • Weekdays with isoWeekday isn't properly distributed on yAxis

    Weekdays with isoWeekday isn't properly distributed on yAxis

    I came across an issue with the nice Matrix plugin. Took your sample matrix-on-time2 to explain it. Only changed the bits important for this issue.

    <!doctype html>
    <html>
    <head>
    	<title>Matrix Chart on time scale 2</title>
    	<script src="https://cdn.jsdelivr.net/npm/[email protected]/moment.min.js"></script>
    	<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.js"></script>
    	<script src="utils.js"></script>
    	<link rel="stylesheet" type="text/css" href="style.css"></link>
    </head>
    <body>
    	<div id="canvas-holder">
    		<canvas id="chart-area" width="800" height="100"></canvas>
    	</div>
    
    
    <script>
    	function generateData() {
    		var data = [];
    		var dt = moment().subtract(365, 'days').startOf('day');
    		var end = moment().startOf('day');
    		while(dt <= end) {
    			data.push({
    				x: dt.format('YYYY-MM-DD'),
    				y: dt.format('E'),
    				d: dt.format('YYYY-MM-DD'),
    				v: Math.random() * 50
    			});
    			dt = dt.add(1, 'day');
    		}
    		return data;
    	}
    
    	Utils.load(function() {
    		Chart.defaults.global.defaultFontSize = 9;
    		var ctx = document.getElementById("chart-area").getContext("2d");
    		window.myMatrix = new Chart(ctx, {
    			type: 'matrix',
    			data: {
    				datasets: [{
    					label: 'My Matrix',
    					data: generateData(),
    					backgroundColor: function(ctx) {
    						var value = ctx.dataset.data[ctx.dataIndex].v;
    						var alpha = (10 + value) / 60;
    						return Color('green').alpha(alpha).rgbString();
    					},
    					borderColor: function(ctx) {
    						var value = ctx.dataset.data[ctx.dataIndex].v;
    						var alpha = (10 + value) / 60;
    						return Color('green').alpha(alpha).darken(0.3).rgbString();
    					},
    					borderWidth: 1,
    					borderSkipped: false,
    					hoverBorderColor: 'yellow',
    					width: function(ctx) {
    						var a = ctx.chart.chartArea;
    						return (a.right - a.left) / 60;
    					},
    					height: function(ctx) {
    						var a = ctx.chart.chartArea;
    						return (a.bottom - a.top) / 7 - 3;
    					}
    				}]
    			},
    			options: {
    				legend: {
    					display: false
    				},
    				tooltips: {
    					displayColors: false,
    					callbacks: {
    						title: function() { return '';},
    						label: function(item, data) {
    							var v = data.datasets[item.datasetIndex].data[item.index];
    							return ["d: " + v.d, "v: " + v.v.toFixed(2)];
    						}
    					}
    				},
    				scales: {
    					xAxes: [{
    						type: 'time',
    						position: 'bottom',
    						offset: true,
    						time: {
    							isoWeekday: true,
    							unit: 'week',
    							round: 'week',
    							displayFormats: {
    								week: 'MMM DD'
    							}
    						},
    						ticks: {
    							maxRotation: 0,
    							autoSkip: true
    						},
    						gridLines: {
    							display: false,
    							drawBorder: false,
    							tickMarkLength: 0,
    						}
    					}],
    					yAxes: [{
    						type: 'time',
    						offset: true,
    						position: 'right',
    						time: {
    							unit: 'day',
    							parser: 'E',
    							displayFormats: {
    								day: 'ddd'
    							}
    						},
    						ticks: {
    							 // workaround, see: https://github.com/chartjs/Chart.js/pull/6257
    							maxRotation: 90
    						},
    						gridLines: {
    							display: false,
    							drawBorder: false,
    							tickMarkLength: 0
    						}
    					}]
    				}
    			}
    		})
    	});
    </script>
    </body>
    

    What did i change? The parser: 'E' instead of 'e', both in generateData() and the yAxed and isoWeekday: true

    This creates: matrix-iso

    As you can see the days on the x axis are european weekdays BUT the sunday is still sorted in the non-european way. Now it's in the column of the american format. Seems like the isoWeekday doesn't work.

    opened by dave-driesmans 4
  • Datasets with X/Y values that don't map directly to the scale labels

    Datasets with X/Y values that don't map directly to the scale labels

    Is there a way to keep dataset X/Y values generic, numeric, while the displayed scale labels as human readable values?

    With a category scale type where the labels need to be multilingual I would have to regenerate the dataset data with translated values, just so the cell will be placed correctly.

    Here's an example of my dataset:

    {x: 1, y: 1, v: 1}
    1: {x: 1, y: 2, v: 2}
    2: {x: 1, y: 3, v: 3}
    3: {x: 1, y: 4, v: 4}
    4: {x: 1, y: 5, v: 5}
    5: {x: 2, y: 1, v: 2}
    6: {x: 2, y: 2, v: 4}
    7: {x: 2, y: 3, v: 6}
    8: {x: 2, y: 4, v: 8}
    9: {x: 2, y: 5, v: 10}
    10: {x: 3, y: 1, v: 3}
    11: {x: 3, y: 2, v: 6}
    12: {x: 3, y: 3, v: 9}
    13: {x: 3, y: 4, v: 12}
    ...
    

    Here's my scales:

              scales: {
                x: { // impact
                  type: 'category',
                  labels: [ 'Insignificant', 'Minor', 'Moderate', 'Major', 'Severe' ],
                  ticks: {
                    stepSize: 1,
                    display: true
                  },
                  grid: {
                    display: false
                  }
                },
                y: { // likelihood
                  type: 'category',
                  labels: [ 'Rare', 'Unlikely', 'Possible', 'Likely', 'Certain' ],
                  offset: true,
                  ticks: {
                    stepSize: 1,
                    display: true
                  },
                  grid: {
                    display: false
                  }
                }
              }
    

    Here's the result:

    image

    If I switch to linear I have no control over the label names but the dataset is placed correctly:

    image

    Basically its not practical or efficient to require the dataset X/Y values to make to the label names if the label needs to change or differ where the value is larger. If I have a large chart (100x50) and the X/Y labels are names, I have to generate the dataset with every name in it.

    Maybe I'm missing someone or there's a sample that covers this. Any tips would be great. Thanks for the great plugin!

    opened by duhmojo 3
Releases(v1.3.0)
Owner
Jukka Kurkela
Programmer of various languages and architectures since 1980's
Jukka Kurkela
Chart.js module for creating sankey diagrams

chartjs-chart-sankey Chart.js v3.3.x module for creating sankey diagrams Browser support All modern and up-to-date browsers are supported, including,

Jukka Kurkela 85 Jan 2, 2023
Smoothie Charts: smooooooth JavaScript charts for realtime streaming data

Smoothie Charts is a really small charting library designed for live streaming data. I built it to reduce the headaches I was getting from watching ch

Joe Walnes 2.2k Dec 13, 2022
J2CL and GWT Charts library based on CHART.JS

Charba - J2CL and GWT Charts library based on CHART.JS What's Charba GWT Web toolkit doesn't have charting library available out of the box. There are

Pepstock.org 56 Dec 17, 2022
Beautiful charts for Angular based on Chart.js

ng2-charts slack Beautiful charts for Angular based on Chart.js Usage & Demo Samples using ng2-charts https://valor-software.com/ng2-charts/ Installat

Valor Software 2.2k Jan 4, 2023
Chart.js plugin to create charts with a hand-drawn, sketchy, appearance

chartjs-plugin-rough Chart.js plugin to create charts with a hand-drawn, sketchy, appearance Version 0.2 requires Chart.js 2.7.0 or later, and Rough.j

Akihiko Kusanagi 73 Dec 1, 2022
Chart.js Box Plots and Violin Plot Charts

Chart.js Box and Violin Plot Chart.js module for charting box and violin plots. This is a maintained fork of @datavisyn/chartjs-chart-box-and-violin-p

Samuel Gratzl 61 Dec 14, 2022
A Simple Dashboard Chart in Laravel Nova using Chart JS

A Simple Dashboard Chart in Laravel Nova using Chart JS. Starting create your own dashboard with Chart JS Integration can save your time and help you maintain consistency across standard elements such as Bar, Stacked, Line, Area, Doughnut and Pie Chart.

Kuncoro Wicaksono 177 Jan 4, 2023
Chart.js plugin to defer initial chart updates

Chart.js plugin to defer initial chart updates until the user scrolls and the canvas appears inside the viewport, and thus trigger the initial chart a

Chart.js 97 Nov 9, 2022
Bar Funnel Chart extension for Chart.js

Chart.BarFunnel.js Provides a Bar Funnel Chart for use with Chart.js Documentation To create a Bar Funnel Chart, include Chart.BarFunnel.js after Char

Chart.js 58 Nov 24, 2022
TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies

TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies; use it with any framework or backend.

null 24 Dec 12, 2022
Reusable JavaScript library for creating sketchy/hand-drawn styled charts in the browser.

roughViz.js is a reusable JavaScript library for creating sketchy/hand-drawn styled charts in the browser, based on D3v5, roughjs, and handy. Why? Use

Jared Wilber 6.4k Jan 4, 2023
JQuery plugin for creating charts

JQuery Linechart JQuery plugin for building a linechart. Chart ruler completely on HTML/CSS/JS. Bar chart, calendar view visualisation. Diagram, graph

Kirill Stepkin 42 Oct 25, 2022
JQuery plugin for creating charts

JQuery Linechart JQuery plugin for building a linechart. Chart ruler completely on HTML/CSS/JS. Bar chart, calendar view visualisation. Diagram, graph

Kirill Stepkin 42 Oct 25, 2022
Chart.js module for charting financial securities

Chart.js Financial Charting Chart.js module for Candlestick and OHLC charts Roadmap Chart.js 2.7.0 added our timeseries scale as new option called dis

Chart.js 630 Dec 29, 2022
Simple HTML5 Charts using the tag

Simple yet flexible JavaScript charting for designers & developers Documentation Currently, there are two versions of the library (2.9.4 and 3.x.x). V

Chart.js 59.4k Jan 7, 2023
Simple responsive charts

Big welcome by the Chartist Guy Checkout the documentation site at http://gionkunz.github.io/chartist-js/ Checkout this lightning talk that gives you

Gion Kunz 26 Dec 30, 2022
Simple, responsive, modern SVG Charts with zero dependencies

Frappe Charts GitHub-inspired modern, intuitive and responsive charts with zero dependencies Explore Demos » Edit at CodePen » Contents Installation U

Frappe 14.6k Jan 4, 2023
📊 A highly interactive data-driven visualization grammar for statistical charts.

English | 简体中文 G2 A highly interactive data-driven visualization grammar for statistical charts. Website • Tutorial Docs • Blog • G2Plot G2 is a visua

AntV team 11.5k Dec 30, 2022
JavaScript diagramming library for interactive flowcharts, org charts, design tools, planning tools, visual languages.

GoJS, a JavaScript Library for HTML Diagrams GoJS is a JavaScript and TypeScript library for creating and manipulating diagrams, charts, and graphs. S

Northwoods Software Corporation 6.6k Dec 30, 2022