Git Product home page Git Product logo

chartjs-chart-error-bars's Introduction

Chart.js Error Bars

License: MIT NPM Package Github Actions

Chart.js module for charting error bars plots. This plugin extends the several char types (bar, line, scatter, polarArea) with their error bar equivalent (barWithErrorBars, lineWithErrorBars, scatterWithErrorBars, polarAreaWithErrorBars).

Bar Chart

bar char with error bars

Horizontal Bar Chart

horizontal bar chart with error bars

Line Chart

line chart with error bars

Scatterplot

scatter plot with error bars

Polar Area plot

polar area plot with error bars

Related Plugins

Check out also my other chart.js plugins:

Install

npm install --save chart.js chartjs-chart-error-bars

Usage

see Examples

and Open in CodePen

Styling

Several new styling keys are added to the individual chart types

Data structure

The data structure depends on the chart type. It uses the fact that chart.js is supporting scatterplots. Thus, it is already prepared for object values.

Chart types: bar and line

see TypeScript Interface:

IErrorBarXDataPoint

Chart type: bar with indexAxis: 'y'

IErrorBarYDataPoint

Chart type: scatter

a combination of the previous two ones

IErrorBarXDataPoint

and

IErrorBarYDataPoint

Chart type: polarArea

IErrorBarRDataPoint

Multiple Error Bars

Multiple error bars are supported.

multiple error bars

Styling

The styling options support different array version.

Note: as with other chart.js style options, using an array will be one value per dataset. Thus, to specify the values for different error bars, one needs to wrap it in an object with a v key having the value itself. The outer for the dataset, the inner for the error bars.

see TypeScript interface:

IErrorBarOptions

Data structure

Just use array of numbers for the corresponding data structures attributes (xMin, xMax, yMin, yMax). The error bars will be rendered in reversed order. Thus, by convention the most inner error bar is in the first place.

e.g.

{
  y: 4,
  yMin: [2, 1],
  yMax: [5, 6]
}

ESM and Tree Shaking

The ESM build of the library supports tree shaking thus having no side effects. As a consequence the chart.js library won't be automatically manipulated nor new controllers automatically registered. One has to manually import and register them.

Variant A:

import Chart, { LinearScale, CategoryScale } from 'chart.js';
import { BarWithErrorBarsController, BarWithErrorBar } from 'chartjs-chart-error-bars';

// register controller in chart.js and ensure the defaults are set
Chart.register(BarWithErrorBarsController, BarWithErrorBar, LinearScale, CategoryScale);

const chart = new Chart(document.getElementById('canvas').getContext('2d'), {
  type: BarWithErrorBarsController.id,
  data: {
    labels: ['A', 'B'],
    datasets: [
      {
        data: [
          {
            y: 4,
            yMin: 1,
            yMax: 6,
          },
          {
            y: 2,
            yMin: 1,
            yMax: 4,
          },
        ],
      },
    ],
  },
});

Variant B:

import { BarWithErrorBarsChart } from 'chartjs-chart-error-bars';

const chart = new BarWithErrorBarsChart(document.getElementById('canvas').getContext('2d'), {
  data: {
    //...
  },
});

Development Environment

npm i -g yarn
yarn install
yarn sdks vscode

Building

yarn install
yarn build

chartjs-chart-error-bars's People

Contributors

dependabot[bot] avatar sgratzl avatar trambi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

chartjs-chart-error-bars's Issues

Line with error bars fails for linear scale

When I use a linear scale and a lineWithErrorBars chart, nothing is drawn. Works fine for category scales.

To Reproduce

  1. Navigate to https://codepen.io/mossymaker/pen/zYRmwPP2.

Expected behavior

Line with error bars is drawn on a linear scale.

Screenshots

image

Context

  • Version: 3
  • Browser: Safari 15.6.1

Additional context

There's a comment in the Pen to toggle between the scale types. Here's the config I used:

new Chart(document.getElementById('canvas').getContext('2d'), {
  type: 'lineWithErrorBars',
  data: {
    datasets: [
      {
        data: [
          {
            x: 1,
            y: 4,
            yMin: 1,
            yMax: 6,
          },
          {
            x: 2,
            y: 2,
            yMin: 1,
            yMax: 4,
          },
        ],
      },
    ],
  },
  options: {
    animation: false,
    scales: {
      // x: {
      //   type: 'category',
      //   labels: ['A', 'B']
      // },
      x: { type: 'linear'}
    },
  },
});

Error: "barWithErrorBars" is not a chart type.

I am trying to include the library in my application built in vue, but when I try to add the graphic with type: "barWithErrorBars" I get the mentioned error.

I have these versions in my package.json:
"chart.js": "^ 2.9.4",
"chartjs-chart-error-bars": "^ 1.2.1",
"vue": "^ 2.5.2",


This is my component:

<template>
  <canvas id="canvas"></canvas>
</template>

<script>
import Chart from 'chart.js'
export default {
  name: 'ErrorBar',
  mounted () {
    let chart = new Chart(document.getElementById('canvas').getContext('2d'), {
      type: 'barWithErrorBars',
      data: {
        labels: ['A', 'B'],
        datasets: [
          {
            data: [
              {
                y: 4,
                yMin: 1,
                yMax: 6
              },
              {
                y: 2,
                yMin: 1,
                yMax: 4
              }
            ]
          }
        ]
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true
              }
            }
          ]
        }
      }
    })
    return chart
  }
}
</script>

<style scoped>
canvas {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}
</style>

Am I doing something wrong?

Could you please help me?

Thanks!

Is there a .js file to import the plugin?

Great plugin!
Is there a .js file we can import to load the plugin into sites?
I don't use NPM and wondered if it was available somewhere.

I can see the samples point to a "build" directory that contains the js, but it is not in the git tree.

Thanks in advance
Pedro

elements.point configurations does not apply in lineWithErrorBars

I,m using lineWithErrorBars, and when I try to set elements.point configs both locally on chart object and through Chart.defaults it seems that desired configuration does not apply.

To Reproduce

Chart.defaults.elements.point.radius = 10

//or

new Chart(document.getElementById('canvas').getContext('2d'), {
            type: 'lineWithErrorBars',
            options: {
                elements: {
                    point:{
                        radius: 10
                    }
                }
            },
            data: {
                labels: labels,
                datasets: datasets
            },
        });

Context

Thank you in advance for your great work.

Error bar color: Use default dataset color if not provided

Lack of default color for error bars decreases the readability of line plots, when multiple datasets are plotted:
Screenshot 2024-04-09 at 12 03 25
https://codepen.io/wwerkk/pen/poBVjZb

It would be great to use default colors of the dataset, if error bar color is not specified, akin to the datavisyn plugin:

https://github.com/datavisyn/chartjs-plugin-error-bars?tab=readme-ov-file#options

There is a way of working around this, but it's unwieldy as afaik the Chart object has to be created first:

        const chart = new Chart(canvas, {
          type: "lineWithErrorBars",
          data,
          options,
        });
        for (let dataset of chart.data.datasets) {
          dataset.errorBarColor = dataset.borderColor;
          dataset.errorBarWhiskerColor = dataset.borderColor;
        }

String Parsing with Min / Max Values

When I attempt to generate an Error Bar chart using string data for data points, the error bars do not generate. If I use numerical values (float or int) the error bars generate.

This is a minor bug and I can get around it by just ensuring data is numerical, but the behavior seems inconsistent with how data is handled for the default Chart.js data points.

Side note: thank you for the excellent plugin!

To Reproduce

  1. Generate a basic Error Bar chart with min / max values as a string data type.
  2. Chart will load with normal data points, but error bars do not load.

Expected behavior

Min / max data points allow string and numerical data.

Context

  • Version: 4.2.0
  • Browser: Any

LineWithErrorBars does not render when using scale of type time

When trying to render LineWithErrorBars having an x Axis scale of type "time" nothing is rendered.
Using the exact same config but changing to scatterWithErrorBars works as expected.

Context
I'm relatively sure this is not browser related, using chartjs>4

Additional context
I think the issue is related to this check:
https://github.com/sgratzl/chartjs-chart-error-bars/blob/main/src/controllers/LineWithErrorBarsController.ts#L61
Maybe adding "time" as check for also being a "hasNumberIScale" might do the trick.

Uncaught Error: "barWithErrorBars" is not a registered controller (v3.9.1)

When I import the plugin while using this with react-chartjs-2 i get the error below

Uncaught Error: "barWithErrorBars" is not a registered controller.
    at Registry._get (chart.esm.js:4916:13)
    at Registry.getController (chart.esm.js:4862:17)
    at Chart.buildOrUpdateControllers (chart.esm.js:5610:42)
    at Chart.update (chart.esm.js:5644:33)
    at new Chart (chart.esm.js:5426:12)
    at renderChart (chart.tsx:42:24)
    at chart.tsx:98:5
    at invokePassiveEffectCreate (react-dom.development.js:23487:20)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:3945:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:16)

looking through the getController function i see that these are registered:

pointWithErrorBar plugin
barWithErrorBars plugin
barWithErrorBar plugin
pointWithErrorBar plugin
barWithErrorBars plugin
barWithErrorBar plugin
pointWithErrorBar plugin
barWithErrorBars plugin
barWithErrorBar plugin
barWithErrorBars controller throws

To Reproduce

that's a rough code (not complete, but the essentials are here)

import { ChartData, ChartOptions, Point, Chart as ChartJS, BarControllerChartOptions } from 'chart.js';
import {
  BarWithErrorBar,
  BarWithErrorBarsController,
  PointWithErrorBar,
  BarWithErrorBarsChart,
} from 'chartjs-chart-error-bars';

// these all registers i tries to add
ChartJS.register(
  PointWithErrorBar,
  BarWithErrorBarsController,
  BarWithErrorBar,
  BarWithErrorBarsChart,
  LinearScale,
  CategoryScale,
  BarElement,
  LinearScale,
  PointElement,
  LineElement,
  TimeScale,
  CategoryScale,
  Title,
  Tooltip,
  Legend,
  Decimation,
  Tooltip,
  Legend,
  annotationPlugin
);

const options = {
            annotations,
            scales: {
              x: {
                type: 'time',
                ticks: {
                  source: 'auto',
                },
              },
              y: {
                suggestedMin: 0,
              },
            },
          };

const getChartDatasets = (data:IErrorBarXYDataPoint[]): ChartData<'barWithErrorBars'> => ({
  labels: data.map(({ x }) => x),
  datasets: [
    {
      data,
    },
  ],
});


const BarChartWithErrors = () => {
return <Chart
        type="barWithErrorBars"
        data={chartDatasets}
        options={chartOptions}
        plugins={[chartUtils.backgroundPlugin]}
      />
}

Expected behavior
after registering BarWithErrorBarsController i expect it to not throw saying it's not registered

Screenshots
image

Context

  • Version: latest
  • Browser: chrome latest
    "chart.js": "3.9.1",
    "chartjs-adapter-dayjs-3": "1.2.3",
    "chartjs-chart-error-bars": "3.9.0",
    "chartjs-plugin-annotation": "1.4.0",
    "react-chartjs-2": "4.3.1",

chart-error-bars on Line Graph

Can you please share how to use chart-error bars on Line Graph?
I am trying to use 'lineWithErrorBars' but it is not working out.

ie11 compatibility

Describe the bug
When I try to use chartjs error bar library on ec2 (centOS) in AWS with IE11, I get the following error: Object doesn't support property or method 'assign'. But I do not get this issue with Google Chrome or Firefox.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Add style options to readme?

Great plugin but I just had to go digging to find out how to change the error bar and whisker color.

Happy to help with that if needed.

Sample documentation for styling

Hello,

could you add a styling example in the documentation ? I'm not fluent using ChartJS and I didn't manage to style error bars, where should I put the configuration options ?

lineWithErrorBars

Hi Team,
We are facing issue to create Line chart with error bars(lineWithErrorBars). We are getting issue with canvas context issue s undefined,
Where same configuration working with barWithErrorBars.
So if possible can you provide the reference code for lineWithErrorBars . We are using chart js 3.6.0 version and chartjs-chart-error-bars/v/3.6.0 version.
above mentioned npm packges we are using with angular 12.

Thanks,
M.dev

Removing y-axis labels

I'm trying to remove the y-label axes with the "scatterWithErrorBars". I tried some solution I found on SO, but none of them worked, so was thinking it was because this was more specific to the errorBar code?

This is what it looks like now:
image

This is what I want it to look like:
image

here's my code:

function generateErrorBarChart(min, max, meas, paramName, id) {
    let minimum = parseFloat(toFixed(min, 2));
    let maximum = parseFloat(toFixed(max, 2));
    let measured = parseFloat(toFixed(meas, 2));

    if (maximum < minimum && maximum == 0) {
        maximum = minimum + 1000;
    }

    new Chart(document.getElementById(id).getContext('2d'), {
        type: 'scatterWithErrorBars',
        options: options,
        data: {
            labels: [paramName],
            datasets: [
                {
                    data: [
                        {
                            x: minimum,
                            y: 0,
                            xMin: minimum,
                            xMax: maximum,
                        },
                        {
                            x: maximum,
                            y: 0,
                            xMin: minimum,
                            xMax: maximum,
                        },
                        {
                            x: measured,
                            y: 0,
                        }
                    ],
                    fill: true,
                    borderColor: 'rgb(255, 0, 0)',
                    tension: 0.8
                },
            ]
        },
    });
}

var options =
{
    plugins: {
        legend: {
            display: false
        }
    }
};


function toFixed(value, precision) {
    var precision = precision || 0,
        power = Math.pow(10, precision),
        absValue = Math.abs(Math.round(value * power)),
        result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));

    if (precision > 0) {
        var fraction = String(absValue % power),
            padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
        result += '.' + padding + fraction;
    }
    return result;
}

AMD import of helpers

You have bug when importing helpers as AMD. Chart.js docs says:

In UMD, helpers are available through Chart.helpers. In ESM, they are imported from chart.js/helpers

Fix in index.umd
add new line 13:
if (!helpers) helpers = chart_js.helpers;
modify line 10 (remove chart.js/helpers):
typeof define === 'function' && define.amd ? define(['exports', 'chart.js'], factory) :

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.