language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
chartjs
Chart.js
aa0933e040b456e23557a999408f6047578e631c.json
Avoid meta data access in calculateCircumference Fix access of uninitialized meta data while calculating circumference in the polar area chart by caching the number of visible elements in the update() method. Also make the calculateTotal() of the doughnut chart tolerant of uninitialized meta data.
src/controllers/controller.polarArea.js
@@ -119,6 +119,7 @@ module.exports = function(Chart) { }, update: function update(reset) { + var meta = this.getMeta(); var minSize = Math.min(this.chart.chartArea.right - this.chart.chartArea.left, this.chart.chartArea.bottom - this.chart.chartArea.top); this.chart.outerRadius = Math.max((minSize - this.chart.options.elements.arc.borderWidth / 2) / 2, 0); this.chart.innerRadius = Math.max(this.chart.options.cutoutPercentage ? (this.chart.outerRadius / 100) * (this.chart.options.cutoutPercentage) : 1, 0); @@ -127,7 +128,9 @@ module.exports = function(Chart) { this.outerRadius = this.chart.outerRadius - (this.chart.radiusLength * this.index); this.innerRadius = this.outerRadius - this.chart.radiusLength; - helpers.each(this.getMeta().data, function(arc, index) { + meta.count = this.countVisibleElements(); + + helpers.each(meta.data, function(arc, index) { this.updateElement(arc, index, reset); }, this); }, @@ -218,23 +221,27 @@ module.exports = function(Chart) { arc._model.borderWidth = arc.custom && arc.custom.borderWidth ? arc.custom.borderWidth : helpers.getValueAtIndexOrDefault(this.getDataset().borderWidth, index, this.chart.options.elements.arc.borderWidth); }, - calculateCircumference: function(value) { - if (isNaN(value)) { - return 0; - } - - // Count the number of "visible"" values + countVisibleElements: function() { + var dataset = this.getDataset(); var meta = this.getMeta(); var count = 0; - this.getDataset().data.forEach(function(value, index) { - if (!isNaN(value) && !meta.data[index].hidden) { + helpers.each(meta.data, function(element, index) { + if (!isNaN(dataset.data[index]) && !element.hidden) { count++; } }); - return (2 * Math.PI) / count; + return count; + }, + + calculateCircumference: function(value) { + var count = this.getMeta().count; + if (count > 0 && !isNaN(value)) { + return (2 * Math.PI) / count; + } else { + return 0; + } } }); - };
true
Other
chartjs
Chart.js
29115c9d2c94f5f52a22fa5e9d39244726a7d9d2.json
Handle data visibility per chart New Chart.Element.hidden bool flag storing the visibility state of its associated data. Since elements belong to a specific chart, this change allows to manage data visibility per chart (e.g. when clicking the legend of some charts). This commit also changes (fixes?) the polar chart animation when data visibility changes. Previous implementation was affected by an edge effect due to the use of NaN as hidden implementation.
src/controllers/controller.doughnut.js
@@ -38,8 +38,9 @@ module.exports = function(Chart) { var data = chart.data; if (data.labels.length && data.datasets.length) { return data.labels.map(function(label, i) { + var meta = chart.getDatasetMeta(0); var ds = data.datasets[0]; - var arc = chart.getDatasetMeta(0).data[i]; + var arc = meta.data[i]; var fill = arc.custom && arc.custom.backgroundColor ? arc.custom.backgroundColor : helpers.getValueAtIndexOrDefault(ds.backgroundColor, i, this.chart.options.elements.arc.backgroundColor); var stroke = arc.custom && arc.custom.borderColor ? arc.custom.borderColor : helpers.getValueAtIndexOrDefault(ds.borderColor, i, this.chart.options.elements.arc.borderColor); var bw = arc.custom && arc.custom.borderWidth ? arc.custom.borderWidth : helpers.getValueAtIndexOrDefault(ds.borderWidth, i, this.chart.options.elements.arc.borderWidth); @@ -49,7 +50,7 @@ module.exports = function(Chart) { fillStyle: fill, strokeStyle: stroke, lineWidth: bw, - hidden: isNaN(data.datasets[0].data[i]), + hidden: isNaN(ds.data[i]) || meta.data[i].hidden, // Extra data used for toggling the correct item index: i @@ -60,20 +61,18 @@ module.exports = function(Chart) { } } }, + onClick: function(e, legendItem) { - helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { - var meta = this.chart.getDatasetMeta(datasetIndex); - var idx = legendItem.index; - - if (!isNaN(dataset.data[idx])) { - meta.hiddenData[idx] = dataset.data[idx]; - dataset.data[idx] = NaN; - } else if (!isNaN(meta.hiddenData[idx])) { - dataset.data[idx] = meta.hiddenData[idx]; - } - }, this); + var index = legendItem.index; + var chart = this.chart; + var i, ilen, meta; + + for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + meta.data[index].hidden = !meta.data[index].hidden; + } - this.chart.update(); + chart.update(); } }, @@ -181,12 +180,7 @@ module.exports = function(Chart) { this.chart.offsetX = offset.x * this.chart.outerRadius; this.chart.offsetY = offset.y * this.chart.outerRadius; - this.getDataset().total = 0; - helpers.each(this.getDataset().data, function(value) { - if (!isNaN(value)) { - this.getDataset().total += Math.abs(value); - } - }, this); + this.getMeta().total = this.calculateTotal(); this.outerRadius = this.chart.outerRadius - (this.chart.radiusLength * this.getRingIndex(this.index)); this.innerRadius = this.outerRadius - this.chart.radiusLength; @@ -195,12 +189,13 @@ module.exports = function(Chart) { this.updateElement(arc, index, reset); }, this); }, + updateElement: function(arc, index, reset) { var centerX = (this.chart.chartArea.left + this.chart.chartArea.right) / 2; var centerY = (this.chart.chartArea.top + this.chart.chartArea.bottom) / 2; var startAngle = this.chart.options.rotation; // non reset case handled later var endAngle = this.chart.options.rotation; // non reset case handled later - var circumference = reset && this.chart.options.animation.animateRotate ? 0 : this.calculateCircumference(this.getDataset().data[index]) * (this.chart.options.circumference / (2.0 * Math.PI)); + var circumference = reset && this.chart.options.animation.animateRotate ? 0 : arc.hidden? 0 : this.calculateCircumference(this.getDataset().data[index]) * (this.chart.options.circumference / (2.0 * Math.PI)); var innerRadius = reset && this.chart.options.animation.animateScale ? 0 : this.innerRadius; var outerRadius = reset && this.chart.options.animation.animateScale ? 0 : this.outerRadius; @@ -269,9 +264,23 @@ module.exports = function(Chart) { arc._model.borderWidth = arc.custom && arc.custom.borderWidth ? arc.custom.borderWidth : helpers.getValueAtIndexOrDefault(this.getDataset().borderWidth, index, this.chart.options.elements.arc.borderWidth); }, + calculateTotal: function() { + var meta = this.getMeta(); + var total = 0; + + this.getDataset().data.forEach(function(value, index) { + if (!isNaN(value) && !meta.data[index].hidden) { + total += Math.abs(value); + } + }); + + return total; + }, + calculateCircumference: function(value) { - if (this.getDataset().total > 0 && !isNaN(value)) { - return (Math.PI * 2.0) * (value / this.getDataset().total); + var total = this.getMeta().total; + if (total > 0 && !isNaN(value)) { + return (Math.PI * 2.0) * (value / total); } else { return 0; }
true
Other
chartjs
Chart.js
29115c9d2c94f5f52a22fa5e9d39244726a7d9d2.json
Handle data visibility per chart New Chart.Element.hidden bool flag storing the visibility state of its associated data. Since elements belong to a specific chart, this change allows to manage data visibility per chart (e.g. when clicking the legend of some charts). This commit also changes (fixes?) the polar chart animation when data visibility changes. Previous implementation was affected by an edge effect due to the use of NaN as hidden implementation.
src/controllers/controller.polarArea.js
@@ -39,8 +39,9 @@ module.exports = function(Chart) { var data = chart.data; if (data.labels.length && data.datasets.length) { return data.labels.map(function(label, i) { + var meta = chart.getDatasetMeta(0); var ds = data.datasets[0]; - var arc = chart.getDatasetMeta(0).data[i]; + var arc = meta.data[i]; var fill = arc.custom && arc.custom.backgroundColor ? arc.custom.backgroundColor : helpers.getValueAtIndexOrDefault(ds.backgroundColor, i, this.chart.options.elements.arc.backgroundColor); var stroke = arc.custom && arc.custom.borderColor ? arc.custom.borderColor : helpers.getValueAtIndexOrDefault(ds.borderColor, i, this.chart.options.elements.arc.borderColor); var bw = arc.custom && arc.custom.borderWidth ? arc.custom.borderWidth : helpers.getValueAtIndexOrDefault(ds.borderWidth, i, this.chart.options.elements.arc.borderWidth); @@ -50,7 +51,7 @@ module.exports = function(Chart) { fillStyle: fill, strokeStyle: stroke, lineWidth: bw, - hidden: isNaN(data.datasets[0].data[i]), + hidden: isNaN(ds.data[i]) || meta.data[i].hidden, // Extra data used for toggling the correct item index: i @@ -61,20 +62,18 @@ module.exports = function(Chart) { } } }, + onClick: function(e, legendItem) { - helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { - var meta = this.chart.getDatasetMeta(datasetIndex); - var idx = legendItem.index; - - if (!isNaN(dataset.data[idx])) { - meta.hiddenData[idx] = dataset.data[idx]; - dataset.data[idx] = NaN; - } else if (!isNaN(meta.hiddenData[idx])) { - dataset.data[idx] = meta.hiddenData[idx]; - } - }, this); + var index = legendItem.index; + var chart = this.chart; + var i, ilen, meta; + + for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + meta.data[index].hidden = !meta.data[index].hidden; + } - this.chart.update(); + chart.update(); } }, @@ -125,11 +124,6 @@ module.exports = function(Chart) { this.chart.innerRadius = Math.max(this.chart.options.cutoutPercentage ? (this.chart.outerRadius / 100) * (this.chart.options.cutoutPercentage) : 1, 0); this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.chart.getVisibleDatasetCount(); - this.getDataset().total = 0; - helpers.each(this.getDataset().data, function(value) { - this.getDataset().total += Math.abs(value); - }, this); - this.outerRadius = this.chart.outerRadius - (this.chart.radiusLength * this.index); this.innerRadius = this.outerRadius - this.chart.radiusLength; @@ -145,21 +139,23 @@ module.exports = function(Chart) { // If there is NaN data before us, we need to calculate the starting angle correctly. // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data - var notNullIndex = 0; + var visibleCount = 0; + var meta = this.getMeta(); for (var i = 0; i < index; ++i) { - if (!isNaN(this.getDataset().data[i])) { - ++notNullIndex; + if (!isNaN(this.getDataset().data[i]) && !meta.data[i].hidden) { + ++visibleCount; } } - var startAngle = (-0.5 * Math.PI) + (circumference * notNullIndex); - var endAngle = startAngle + circumference; + var distance = arc.hidden? 0 : this.chart.scale.getDistanceFromCenterForValue(this.getDataset().data[index]); + var startAngle = (-0.5 * Math.PI) + (circumference * visibleCount); + var endAngle = startAngle + (arc.hidden? 0 : circumference); var resetModel = { x: centerX, y: centerY, innerRadius: 0, - outerRadius: this.chart.options.animateScale ? 0 : this.chart.scale.getDistanceFromCenterForValue(this.getDataset().data[index]), + outerRadius: this.chart.options.animateScale ? 0 : distance, startAngle: this.chart.options.animateRotate ? Math.PI * -0.5 : startAngle, endAngle: this.chart.options.animateRotate ? Math.PI * -0.5 : endAngle, @@ -182,7 +178,7 @@ module.exports = function(Chart) { x: centerX, y: centerY, innerRadius: 0, - outerRadius: this.chart.scale.getDistanceFromCenterForValue(this.getDataset().data[index]), + outerRadius: distance, startAngle: startAngle, endAngle: endAngle, @@ -225,15 +221,20 @@ module.exports = function(Chart) { calculateCircumference: function(value) { if (isNaN(value)) { return 0; - } else { - // Count the number of NaN values - var numNaN = helpers.where(this.getDataset().data, function(data) { - return isNaN(data); - }).length; - - return (2 * Math.PI) / (this.getDataset().data.length - numNaN); } + + // Count the number of "visible"" values + var meta = this.getMeta(); + var count = 0; + + this.getDataset().data.forEach(function(value, index) { + if (!isNaN(value) && !meta.data[index].hidden) { + count++; + } + }); + + return (2 * Math.PI) / count; } }); -}; \ No newline at end of file +};
true
Other
chartjs
Chart.js
29115c9d2c94f5f52a22fa5e9d39244726a7d9d2.json
Handle data visibility per chart New Chart.Element.hidden bool flag storing the visibility state of its associated data. Since elements belong to a specific chart, this change allows to manage data visibility per chart (e.g. when clicking the legend of some charts). This commit also changes (fixes?) the polar chart animation when data visibility changes. Previous implementation was affected by an edge effect due to the use of NaN as hidden implementation.
src/core/core.controller.js
@@ -416,7 +416,6 @@ module.exports = function(Chart) { data: [], dataset: null, controller: null, - hiddenData: {}, hidden: null, // See isDatasetVisible() comment xAxisID: null, yAxisID: null
true
Other
chartjs
Chart.js
29115c9d2c94f5f52a22fa5e9d39244726a7d9d2.json
Handle data visibility per chart New Chart.Element.hidden bool flag storing the visibility state of its associated data. Since elements belong to a specific chart, this change allows to manage data visibility per chart (e.g. when clicking the legend of some charts). This commit also changes (fixes?) the polar chart animation when data visibility changes. Previous implementation was affected by an edge effect due to the use of NaN as hidden implementation.
src/core/core.element.js
@@ -11,7 +11,9 @@ module.exports = function(Chart) { this.initialize.apply(this, arguments); }; helpers.extend(Chart.Element.prototype, { - initialize: function() {}, + initialize: function() { + this.hidden = false; + }, pivot: function() { if (!this._view) { this._view = helpers.clone(this._model);
true
Other
chartjs
Chart.js
29115c9d2c94f5f52a22fa5e9d39244726a7d9d2.json
Handle data visibility per chart New Chart.Element.hidden bool flag storing the visibility state of its associated data. Since elements belong to a specific chart, this change allows to manage data visibility per chart (e.g. when clicking the legend of some charts). This commit also changes (fixes?) the polar chart animation when data visibility changes. Previous implementation was affected by an edge effect due to the use of NaN as hidden implementation.
src/scales/scale.linear.js
@@ -61,9 +61,8 @@ module.exports = function(Chart) { if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { helpers.each(dataset.data, function(rawValue, index) { - var value = +this.getRightValue(rawValue); - if (isNaN(value)) { + if (isNaN(value) || meta.data[index].hidden) { return; } @@ -99,7 +98,7 @@ module.exports = function(Chart) { if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { helpers.each(dataset.data, function(rawValue, index) { var value = +this.getRightValue(rawValue); - if (isNaN(value)) { + if (isNaN(value) || meta.data[index].hidden) { return; }
true
Other
chartjs
Chart.js
29115c9d2c94f5f52a22fa5e9d39244726a7d9d2.json
Handle data visibility per chart New Chart.Element.hidden bool flag storing the visibility state of its associated data. Since elements belong to a specific chart, this change allows to manage data visibility per chart (e.g. when clicking the legend of some charts). This commit also changes (fixes?) the polar chart animation when data visibility changes. Previous implementation was affected by an edge effect due to the use of NaN as hidden implementation.
src/scales/scale.logarithmic.js
@@ -40,7 +40,7 @@ module.exports = function(Chart) { helpers.each(dataset.data, function(rawValue, index) { var values = valuesPerType[meta.type]; var value = +this.getRightValue(rawValue); - if (isNaN(value)) { + if (isNaN(value) || meta.data[index].hidden) { return; } @@ -66,10 +66,10 @@ module.exports = function(Chart) { } else { helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { var meta = this.chart.getDatasetMeta(datasetIndex); - if (this.chart.isDatasetVisible(dataset, datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { + if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { helpers.each(dataset.data, function(rawValue, index) { var value = +this.getRightValue(rawValue); - if (isNaN(value)) { + if (isNaN(value) || meta.data[index].hidden) { return; }
true
Other
chartjs
Chart.js
29115c9d2c94f5f52a22fa5e9d39244726a7d9d2.json
Handle data visibility per chart New Chart.Element.hidden bool flag storing the visibility state of its associated data. Since elements belong to a specific chart, this change allows to manage data visibility per chart (e.g. when clicking the legend of some charts). This commit also changes (fixes?) the polar chart animation when data visibility changes. Previous implementation was affected by an edge effect due to the use of NaN as hidden implementation.
src/scales/scale.radialLinear.js
@@ -65,9 +65,10 @@ module.exports = function(Chart) { helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { if (this.chart.isDatasetVisible(datasetIndex)) { + var meta = this.chart.getDatasetMeta(datasetIndex); helpers.each(dataset.data, function(rawValue, index) { var value = +this.getRightValue(rawValue); - if (isNaN(value)) { + if (isNaN(value) || meta.data[index].hidden) { return; }
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/controllers/controller.bar.js
@@ -40,7 +40,7 @@ module.exports = function(Chart) { var barCount = 0; helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { var meta = this.chart.getDatasetMeta(datasetIndex); - if (meta.bar && helpers.isDatasetVisible(dataset)) { + if (meta.bar && this.chart.isDatasetVisible(datasetIndex)) { ++barCount; } }, this); @@ -141,15 +141,15 @@ module.exports = function(Chart) { for (var i = 0; i < datasetIndex; i++) { var negDS = this.chart.data.datasets[i]; var negDSMeta = this.chart.getDatasetMeta(i); - if (negDSMeta.bar && negDSMeta.yAxisID === yScale.id && helpers.isDatasetVisible(negDS)) { + if (negDSMeta.bar && negDSMeta.yAxisID === yScale.id && this.chart.isDatasetVisible(i)) { base += negDS.data[index] < 0 ? negDS.data[index] : 0; } } } else { for (var j = 0; j < datasetIndex; j++) { var posDS = this.chart.data.datasets[j]; var posDSMeta = this.chart.getDatasetMeta(j); - if (posDSMeta.bar && posDSMeta.yAxisID === yScale.id && helpers.isDatasetVisible(posDS)) { + if (posDSMeta.bar && posDSMeta.yAxisID === yScale.id && this.chart.isDatasetVisible(j)) { base += posDS.data[index] > 0 ? posDS.data[index] : 0; } } @@ -221,7 +221,7 @@ module.exports = function(Chart) { for (j = 0; j < datasetIndex; ++j) { meta = this.chart.getDatasetMeta(j); - if (meta.bar && helpers.isDatasetVisible(this.chart.data.datasets[j])) { + if (meta.bar && this.chart.isDatasetVisible(j)) { ++barIndex; } } @@ -266,7 +266,7 @@ module.exports = function(Chart) { for (var i = 0; i < datasetIndex; i++) { var ds = this.chart.data.datasets[i]; var dsMeta = this.chart.getDatasetMeta(i); - if (dsMeta.bar && dsMeta.yAxisID === yScale.id && helpers.isDatasetVisible(ds)) { + if (dsMeta.bar && dsMeta.yAxisID === yScale.id && this.chart.isDatasetVisible(i)) { if (ds.data[index] < 0) { sumNeg += ds.data[index] || 0; } else {
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/controllers/controller.doughnut.js
@@ -61,17 +61,17 @@ module.exports = function(Chart) { } }, onClick: function(e, legendItem) { - helpers.each(this.chart.data.datasets, function(dataset) { - dataset.metaHiddenData = dataset.metaHiddenData || []; + helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { + var meta = this.chart.getDatasetMeta(datasetIndex); var idx = legendItem.index; if (!isNaN(dataset.data[idx])) { - dataset.metaHiddenData[idx] = dataset.data[idx]; + meta.hiddenData[idx] = dataset.data[idx]; dataset.data[idx] = NaN; - } else if (!isNaN(dataset.metaHiddenData[idx])) { - dataset.data[idx] = dataset.metaHiddenData[idx]; + } else if (!isNaN(meta.hiddenData[idx])) { + dataset.data[idx] = meta.hiddenData[idx]; } - }); + }, this); this.chart.update(); } @@ -137,18 +137,12 @@ module.exports = function(Chart) { this.updateElement(arc, index, true); }, - getVisibleDatasetCount: function getVisibleDatasetCount() { - return helpers.where(this.chart.data.datasets, function(ds) { - return helpers.isDatasetVisible(ds); - }).length; - }, - // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly getRingIndex: function getRingIndex(datasetIndex) { var ringIndex = 0; for (var j = 0; j < datasetIndex; ++j) { - if (helpers.isDatasetVisible(this.chart.data.datasets[j])) { + if (this.chart.isDatasetVisible(j)) { ++ringIndex; } } @@ -183,7 +177,7 @@ module.exports = function(Chart) { this.chart.outerRadius = Math.max(minSize / 2, 0); this.chart.innerRadius = Math.max(this.chart.options.cutoutPercentage ? (this.chart.outerRadius / 100) * (this.chart.options.cutoutPercentage) : 1, 0); - this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.getVisibleDatasetCount(); + this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.chart.getVisibleDatasetCount(); this.chart.offsetX = offset.x * this.chart.outerRadius; this.chart.offsetY = offset.y * this.chart.outerRadius;
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/controllers/controller.line.js
@@ -223,7 +223,7 @@ module.exports = function(Chart) { for (var i = 0; i < datasetIndex; i++) { var ds = this.chart.data.datasets[i]; var dsMeta = this.chart.getDatasetMeta(i); - if (dsMeta.type === 'line' && helpers.isDatasetVisible(ds)) { + if (dsMeta.type === 'line' && this.chart.isDatasetVisible(i)) { if (ds.data[index] < 0) { sumNeg += ds.data[index] || 0; } else {
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/controllers/controller.polarArea.js
@@ -62,17 +62,17 @@ module.exports = function(Chart) { } }, onClick: function(e, legendItem) { - helpers.each(this.chart.data.datasets, function(dataset) { - dataset.metaHiddenData = dataset.metaHiddenData || []; + helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { + var meta = this.chart.getDatasetMeta(datasetIndex); var idx = legendItem.index; if (!isNaN(dataset.data[idx])) { - dataset.metaHiddenData[idx] = dataset.data[idx]; + meta.hiddenData[idx] = dataset.data[idx]; dataset.data[idx] = NaN; - } else if (!isNaN(dataset.metaHiddenData[idx])) { - dataset.data[idx] = dataset.metaHiddenData[idx]; + } else if (!isNaN(meta.hiddenData[idx])) { + dataset.data[idx] = meta.hiddenData[idx]; } - }); + }, this); this.chart.update(); } @@ -118,17 +118,12 @@ module.exports = function(Chart) { this.getMeta().data.splice(index, 0, arc); this.updateElement(arc, index, true); }, - getVisibleDatasetCount: function getVisibleDatasetCount() { - return helpers.where(this.chart.data.datasets, function(ds) { - return helpers.isDatasetVisible(ds); - }).length; - }, update: function update(reset) { var minSize = Math.min(this.chart.chartArea.right - this.chart.chartArea.left, this.chart.chartArea.bottom - this.chart.chartArea.top); this.chart.outerRadius = Math.max((minSize - this.chart.options.elements.arc.borderWidth / 2) / 2, 0); this.chart.innerRadius = Math.max(this.chart.options.cutoutPercentage ? (this.chart.outerRadius / 100) * (this.chart.options.cutoutPercentage) : 1, 0); - this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.getVisibleDatasetCount(); + this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.chart.getVisibleDatasetCount(); this.getDataset().total = 0; helpers.each(this.getDataset().data, function(value) {
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/core/core.controller.js
@@ -325,7 +325,7 @@ module.exports = function(Chart) { // Draw each dataset via its respective controller (reversed to support proper line stacking) helpers.each(this.data.datasets, function(dataset, datasetIndex) { - if (helpers.isDatasetVisible(dataset)) { + if (this.isDatasetVisible(datasetIndex)) { this.getDatasetMeta(datasetIndex).controller.draw(ease); } }, this, true); @@ -346,8 +346,8 @@ module.exports = function(Chart) { var elementsArray = []; helpers.each(this.data.datasets, function(dataset, datasetIndex) { - var meta = this.getDatasetMeta(datasetIndex); - if (helpers.isDatasetVisible(dataset)) { + if (this.isDatasetVisible(datasetIndex)) { + var meta = this.getDatasetMeta(datasetIndex); helpers.each(meta.data, function(element, index) { if (element.inRange(eventPosition.x, eventPosition.y)) { elementsArray.push(element); @@ -368,7 +368,7 @@ module.exports = function(Chart) { if (this.data.datasets) { for (var i = 0; i < this.data.datasets.length; i++) { var meta = this.getDatasetMeta(i); - if (helpers.isDatasetVisible(this.data.datasets[i])) { + if (this.isDatasetVisible(i)) { for (var j = 0; j < meta.data.length; j++) { if (meta.data[j].inRange(eventPosition.x, eventPosition.y)) { return meta.data[j]; @@ -384,8 +384,8 @@ module.exports = function(Chart) { } helpers.each(this.data.datasets, function(dataset, datasetIndex) { - var meta = this.getDatasetMeta(datasetIndex); - if (helpers.isDatasetVisible(dataset)) { + if (this.isDatasetVisible(datasetIndex)) { + var meta = this.getDatasetMeta(datasetIndex); elementsArray.push(meta.data[found._index]); } }, this); @@ -416,6 +416,8 @@ module.exports = function(Chart) { data: [], dataset: null, controller: null, + hiddenData: {}, + hidden: null, // See isDatasetVisible() comment xAxisID: null, yAxisID: null }; @@ -424,6 +426,24 @@ module.exports = function(Chart) { return meta; }, + getVisibleDatasetCount: function() { + var count = 0; + for (var i = 0, ilen = this.data.datasets.length; i<ilen; ++i) { + if (this.isDatasetVisible(i)) { + count++; + } + } + return count; + }, + + isDatasetVisible: function(datasetIndex) { + var meta = this.getDatasetMeta(datasetIndex); + + // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false, + // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned. + return typeof meta.hidden === 'boolean'? !meta.hidden : !this.data.datasets[datasetIndex].hidden; + }, + generateLegend: function generateLegend() { return this.options.legendCallback(this); },
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/core/core.helpers.js
@@ -938,9 +938,6 @@ module.exports = function(Chart) { array.push(element); } }; - helpers.isDatasetVisible = function(dataset) { - return !dataset.hidden; - }; helpers.callCallback = function(fn, args, _tArg) { if (fn && typeof fn.call === 'function') { fn.apply(_tArg, args);
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/core/core.legend.js
@@ -13,8 +13,11 @@ module.exports = function(Chart) { // a callback that will handle onClick: function(e, legendItem) { - var dataset = this.chart.data.datasets[legendItem.datasetIndex]; - dataset.hidden = !dataset.hidden; + var index = legendItem.datasetIndex; + var meta = this.chart.getDatasetMeta(index); + + // See controller.isDatasetVisible comment + meta.hidden = meta.hidden === null? !this.chart.data.datasets[index].hidden : null; // We hid a dataset ... rerender the chart this.chart.update(); @@ -40,7 +43,7 @@ module.exports = function(Chart) { return { text: dataset.label, fillStyle: dataset.backgroundColor, - hidden: dataset.hidden, + hidden: !chart.isDatasetVisible(i), lineCap: dataset.borderCapStyle, lineDash: dataset.borderDash, lineDashOffset: dataset.borderDashOffset,
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/core/core.tooltip.js
@@ -236,7 +236,7 @@ module.exports = function(Chart) { tooltipPosition = this.getAveragePosition(this._active); } else { helpers.each(this._data.datasets, function(dataset, datasetIndex) { - if (!helpers.isDatasetVisible(dataset)) { + if (!this._chartInstance.isDatasetVisible(datasetIndex)) { return; }
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/scales/scale.linear.js
@@ -59,7 +59,7 @@ module.exports = function(Chart) { var positiveValues = valuesPerType[meta.type].positiveValues; var negativeValues = valuesPerType[meta.type].negativeValues; - if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { + if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { helpers.each(dataset.data, function(rawValue, index) { var value = +this.getRightValue(rawValue); @@ -96,7 +96,7 @@ module.exports = function(Chart) { } else { helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { var meta = this.chart.getDatasetMeta(datasetIndex); - if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { + if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { helpers.each(dataset.data, function(rawValue, index) { var value = +this.getRightValue(rawValue); if (isNaN(value)) {
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/scales/scale.logarithmic.js
@@ -32,7 +32,7 @@ module.exports = function(Chart) { helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { var meta = this.chart.getDatasetMeta(datasetIndex); - if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { + if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { if (valuesPerType[meta.type] === undefined) { valuesPerType[meta.type] = []; } @@ -66,7 +66,7 @@ module.exports = function(Chart) { } else { helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { var meta = this.chart.getDatasetMeta(datasetIndex); - if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { + if (this.chart.isDatasetVisible(dataset, datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { helpers.each(dataset.data, function(rawValue, index) { var value = +this.getRightValue(rawValue); if (isNaN(value)) {
true
Other
chartjs
Chart.js
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf.json
Handle effective dataset visibility per chart Introduced a new meta.hidden 3 states flag (null|true|false) to be able to override dataset.hidden when interacting with the chart (i.e., true or false to ignore the dataset.hidden value). This is required in order to be able to correctly share dataset.hidden between multiple charts. For example: 2 charts are sharing the same data and dataset.hidden is initially false: the dataset will be displayed on both charts because meta.hidden is null. If the user clicks the legend of the first chart, meta.hidden is changed to true and the dataset is only hidden on the first chart. If dataset.hidden changes, only the second chart will have the dataset visibility updated and that until the user click again on the first chart legend, switching the meta.hidden to null.
src/scales/scale.radialLinear.js
@@ -63,8 +63,8 @@ module.exports = function(Chart) { this.min = null; this.max = null; - helpers.each(this.chart.data.datasets, function(dataset) { - if (helpers.isDatasetVisible(dataset)) { + helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { + if (this.chart.isDatasetVisible(datasetIndex)) { helpers.each(dataset.data, function(rawValue, index) { var value = +this.getRightValue(rawValue); if (isNaN(value)) { @@ -395,7 +395,7 @@ module.exports = function(Chart) { } // Extra 3px out for some label spacing var pointLabelPosition = this.getPointPosition(i, this.getDistanceFromCenterForValue(this.options.reverse ? this.min : this.max) + 5); - + var pointLabelFontColor = helpers.getValueOrDefault(this.options.pointLabels.fontColor, Chart.defaults.global.defaultFontColor); var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize); var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle);
true
Other
chartjs
Chart.js
f3457c99417e3e87f67b8b673c6d9ca046b3bc46.json
Handle dataset type per chart Dataset effective type is now stored under meta.type, allowing many charts to share the same dataset but with different types. Also move dataset.bar flag to meta.bar.
src/controllers/controller.bar.js
@@ -33,16 +33,17 @@ module.exports = function(Chart) { Chart.DatasetController.prototype.initialize.call(this, chart, datasetIndex); // Use this to indicate that this is a bar dataset. - this.getDataset().bar = true; + this.getMeta().bar = true; }, // Get the number of datasets that display bars. We use this to correctly calculate the bar width getBarCount: function getBarCount() { var barCount = 0; - helpers.each(this.chart.data.datasets, function(dataset) { - if (helpers.isDatasetVisible(dataset) && dataset.bar) { + helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { + var meta = this.chart.getDatasetMeta(datasetIndex); + if (meta.bar && helpers.isDatasetVisible(dataset)) { ++barCount; } - }); + }, this); return barCount; }, @@ -140,15 +141,15 @@ module.exports = function(Chart) { for (var i = 0; i < datasetIndex; i++) { var negDS = this.chart.data.datasets[i]; var negDSMeta = this.chart.getDatasetMeta(i); - if (helpers.isDatasetVisible(negDS) && negDSMeta.yAxisID === yScale.id && negDS.bar) { + if (negDSMeta.bar && negDSMeta.yAxisID === yScale.id && helpers.isDatasetVisible(negDS)) { base += negDS.data[index] < 0 ? negDS.data[index] : 0; } } } else { for (var j = 0; j < datasetIndex; j++) { var posDS = this.chart.data.datasets[j]; var posDSMeta = this.chart.getDatasetMeta(j); - if (helpers.isDatasetVisible(posDS) && posDSMeta.yAxisID === yScale.id && posDS.bar) { + if (posDSMeta.bar && posDSMeta.yAxisID === yScale.id && helpers.isDatasetVisible(posDS)) { base += posDS.data[index] > 0 ? posDS.data[index] : 0; } } @@ -216,9 +217,11 @@ module.exports = function(Chart) { // Get bar index from the given dataset index accounting for the fact that not all bars are visible getBarIndex: function(datasetIndex) { var barIndex = 0; + var meta, j; - for (var j = 0; j < datasetIndex; ++j) { - if (helpers.isDatasetVisible(this.chart.data.datasets[j]) && this.chart.data.datasets[j].bar) { + for (j = 0; j < datasetIndex; ++j) { + meta = this.chart.getDatasetMeta(j); + if (meta.bar && helpers.isDatasetVisible(this.chart.data.datasets[j])) { ++barIndex; } } @@ -263,7 +266,7 @@ module.exports = function(Chart) { for (var i = 0; i < datasetIndex; i++) { var ds = this.chart.data.datasets[i]; var dsMeta = this.chart.getDatasetMeta(i); - if (helpers.isDatasetVisible(ds) && ds.bar && dsMeta.yAxisID === yScale.id) { + if (dsMeta.bar && dsMeta.yAxisID === yScale.id && helpers.isDatasetVisible(ds)) { if (ds.data[index] < 0) { sumNeg += ds.data[index] || 0; } else {
true
Other
chartjs
Chart.js
f3457c99417e3e87f67b8b673c6d9ca046b3bc46.json
Handle dataset type per chart Dataset effective type is now stored under meta.type, allowing many charts to share the same dataset but with different types. Also move dataset.bar flag to meta.bar.
src/controllers/controller.line.js
@@ -222,7 +222,8 @@ module.exports = function(Chart) { for (var i = 0; i < datasetIndex; i++) { var ds = this.chart.data.datasets[i]; - if (ds.type === 'line' && helpers.isDatasetVisible(ds)) { + var dsMeta = this.chart.getDatasetMeta(i); + if (dsMeta.type === 'line' && helpers.isDatasetVisible(ds)) { if (ds.data[index] < 0) { sumNeg += ds.data[index] || 0; } else {
true
Other
chartjs
Chart.js
f3457c99417e3e87f67b8b673c6d9ca046b3bc46.json
Handle dataset type per chart Dataset effective type is now stored under meta.type, allowing many charts to share the same dataset but with different types. Also move dataset.bar flag to meta.bar.
src/core/core.controller.js
@@ -208,18 +208,17 @@ module.exports = function(Chart) { var newControllers = []; helpers.each(this.data.datasets, function(dataset, datasetIndex) { - if (!dataset.type) { - dataset.type = this.config.type; + var meta = this.getDatasetMeta(datasetIndex); + if (!meta.type) { + meta.type = dataset.type || this.config.type; } - var meta = this.getDatasetMeta(datasetIndex); - var type = dataset.type; - types.push(type); + types.push(meta.type); if (meta.controller) { meta.controller.updateIndex(datasetIndex); } else { - meta.controller = new Chart.controllers[type](this, datasetIndex); + meta.controller = new Chart.controllers[meta.type](this, datasetIndex); newControllers.push(meta.controller); } }, this); @@ -347,7 +346,7 @@ module.exports = function(Chart) { var elementsArray = []; helpers.each(this.data.datasets, function(dataset, datasetIndex) { - var meta = this.getDatasetMeta(datasetIndex); + var meta = this.getDatasetMeta(datasetIndex); if (helpers.isDatasetVisible(dataset)) { helpers.each(meta.data, function(element, index) { if (element.inRange(eventPosition.x, eventPosition.y)) { @@ -376,7 +375,7 @@ module.exports = function(Chart) { } } } - }; + } } }).call(this); @@ -385,7 +384,7 @@ module.exports = function(Chart) { } helpers.each(this.data.datasets, function(dataset, datasetIndex) { - var meta = this.getDatasetMeta(datasetIndex); + var meta = this.getDatasetMeta(datasetIndex); if (helpers.isDatasetVisible(dataset)) { elementsArray.push(meta.data[found._index]); } @@ -413,12 +412,13 @@ module.exports = function(Chart) { var meta = dataset._meta[this.id]; if (!meta) { meta = dataset._meta[this.id] = { - data: [], - dataset: null, - controller: null, - xAxisID: null, - yAxisID: null - }; + type: null, + data: [], + dataset: null, + controller: null, + xAxisID: null, + yAxisID: null + }; } return meta;
true
Other
chartjs
Chart.js
f3457c99417e3e87f67b8b673c6d9ca046b3bc46.json
Handle dataset type per chart Dataset effective type is now stored under meta.type, allowing many charts to share the same dataset but with different types. Also move dataset.bar flag to meta.bar.
src/scales/scale.linear.js
@@ -48,16 +48,16 @@ module.exports = function(Chart) { helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { var meta = this.chart.getDatasetMeta(datasetIndex); - if (valuesPerType[dataset.type] === undefined) { - valuesPerType[dataset.type] = { + if (valuesPerType[meta.type] === undefined) { + valuesPerType[meta.type] = { positiveValues: [], negativeValues: [] }; } // Store these per type - var positiveValues = valuesPerType[dataset.type].positiveValues; - var negativeValues = valuesPerType[dataset.type].negativeValues; + var positiveValues = valuesPerType[meta.type].positiveValues; + var negativeValues = valuesPerType[meta.type].negativeValues; if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { helpers.each(dataset.data, function(rawValue, index) {
true
Other
chartjs
Chart.js
f3457c99417e3e87f67b8b673c6d9ca046b3bc46.json
Handle dataset type per chart Dataset effective type is now stored under meta.type, allowing many charts to share the same dataset but with different types. Also move dataset.bar flag to meta.bar.
src/scales/scale.logarithmic.js
@@ -33,12 +33,12 @@ module.exports = function(Chart) { helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { var meta = this.chart.getDatasetMeta(datasetIndex); if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { - if (valuesPerType[dataset.type] === undefined) { - valuesPerType[dataset.type] = []; + if (valuesPerType[meta.type] === undefined) { + valuesPerType[meta.type] = []; } helpers.each(dataset.data, function(rawValue, index) { - var values = valuesPerType[dataset.type]; + var values = valuesPerType[meta.type]; var value = +this.getRightValue(rawValue); if (isNaN(value)) { return;
true
Other
chartjs
Chart.js
f51d7753bd3dea42e51487831c3b0f6f732460c1.json
Update logarithmic algorithm
src/scales/scale.logarithmic.js
@@ -10,10 +10,10 @@ // label settings ticks: { - callback: function(value) { + callback: function(value, index, arr) { var remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value)))); - if (remain === 1 || remain === 2 || remain === 5) { + if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === arr.length - 1) { return value.toExponential(); } else { return ''; @@ -90,13 +90,8 @@ }, this); } - if (this.options.ticks.max) { - this.max = this.options.ticks.max; - } - - if (this.options.ticks.min) { - this.min = this.options.ticks.min; - } + this.min = this.options.ticks.min !== undefined ? this.options.ticks.min : this.min; + this.max = this.options.ticks.max !== undefined ? this.options.ticks.max : this.max; if (this.min === this.max) { if (this.min !== 0 && this.min !== null) { @@ -118,24 +113,37 @@ // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on // the graph - var minExponent = Math.floor(helpers.log10(this.min)); - var maxExponent = Math.ceil(helpers.log10(this.max)); + var tickVal = this.options.ticks.min !== undefined ? this.options.ticks.min : Math.pow(10, Math.floor(helpers.log10(this.min))); - for (var exponent = minExponent; exponent < maxExponent; ++exponent) { - for (var i = 1; i < 10; ++i) { - this.tickValues.push(i * Math.pow(10, exponent)); + while (tickVal < this.max) { + this.tickValues.push(tickVal); + + var exp = Math.floor(helpers.log10(tickVal)); + var significand = Math.floor(tickVal / Math.pow(10, exp)) + 1; + + if (significand === 10) { + significand = 1; + ++exp; } + + tickVal = significand * Math.pow(10, exp); } - this.tickValues.push(1.0 * Math.pow(10, maxExponent)); + /*var minExponent = Math.floor(helpers.log10(this.min)); + var maxExponent = Math.ceil(helpers.log10(this.max)); - if (this.options.ticks.min) { - this.tickValues[0] = this.min; - } + for (var exponent = minExponent; exponent < maxExponent; ++exponent) { + for (var i = 1; i < 10; ++i) { + if (this.options.ticks.min) { - if (this.options.ticks.max) { - this.tickValues[this.tickValues.length - 1] = this.max; - } + } else { + this.tickValues.push(i * Math.pow(10, exponent)); + } + } + }*/ + + var lastTick = this.options.ticks.max !== undefined ? this.options.ticks.max : tickVal; + this.tickValues.push(lastTick); if (this.options.position == "left" || this.options.position == "right") { // We are in a vertical orientation. The top value is the highest. So reverse the array @@ -147,14 +155,6 @@ this.max = helpers.max(this.tickValues); this.min = helpers.min(this.tickValues); - if (this.options.ticks.min) { - this.min = this.options.ticks.min; - } - - if (this.options.ticks.max) { - this.max = this.options.ticks.max; - } - if (this.options.ticks.reverse) { this.tickValues.reverse();
false
Other
chartjs
Chart.js
e94bd460a795180c7bf5b45245c89f4c23c37ab6.json
Remove Firefox workaround The workaround for older Firefox should be removed, because latest supported Firefox 38.4.0/42.0 do not require it. And it has side effect like #1198 or my problem on Kintone on cybozu.com.
src/Chart.Core.js
@@ -40,10 +40,6 @@ var width = this.width = computeDimension(context.canvas,'Width') || context.canvas.width; var height = this.height = computeDimension(context.canvas,'Height') || context.canvas.height; - // Firefox requires this to work correctly - context.canvas.width = width; - context.canvas.height = height; - width = this.width = context.canvas.width; height = this.height = context.canvas.height; this.aspectRatio = this.width / this.height;
false
Other
chartjs
Chart.js
28fc6841f302d595fdf78f441c6e030fe815dc07.json
Add tooltipFormat option to time scale options. Fix bars when displayed on a time scale. Updated sample files.
docs/01-Scales.md
@@ -153,16 +153,18 @@ The time scale extends the core scale class with the following tick template: // Moment js for each of the units. Replaces `displayFormat` // To override, use a pattern string from http://momentjs.com/docs/#/displaying/format/ displayFormats: { - 'millisecond': 'SSS [ms]', - 'second': 'h:mm:ss a', // 11:20:01 AM - 'minute': 'h:mm:ss a', // 11:20:01 AM - 'hour': 'MMM D, hA', // Sept 4, 5PM - 'day': 'll', // Sep 4 2015 - 'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ? - 'month': 'MMM YYYY', // Sept 2015 - 'quarter': '[Q]Q - YYYY', // Q3 - 'year': 'YYYY', // 2015 - }, + 'millisecond': 'SSS [ms]', + 'second': 'h:mm:ss a', // 11:20:01 AM + 'minute': 'h:mm:ss a', // 11:20:01 AM + 'hour': 'MMM D, hA', // Sept 4, 5PM + 'day': 'll', // Sep 4 2015 + 'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ? + 'month': 'MMM YYYY', // Sept 2015 + 'quarter': '[Q]Q - YYYY', // Q3 + 'year': 'YYYY', // 2015 + }, + // Sets the display format used in tooltip generation + tooltipFormat: '' }, } ```
true
Other
chartjs
Chart.js
28fc6841f302d595fdf78f441c6e030fe815dc07.json
Add tooltipFormat option to time scale options. Fix bars when displayed on a time scale. Updated sample files.
samples/timeScale/combo-time-scale.html
@@ -2,190 +2,179 @@ <html> <head> - <title>Line Chart</title> - <script src="../node_modules/moment/min/moment.min.js"></script> - <script src="../Chart.js"></script> - <script src="../node_modules/jquery/dist/jquery.min.js"></script> - <style> - canvas { - -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, .5); - } - </style> + <title>Line Chart</title> + <script src="../../node_modules/moment/min/moment.min.js"></script> + <script src="../../Chart.js"></script> + <script src="../../node_modules/jquery/dist/jquery.min.js"></script> + <style> + canvas { + -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, .5); + } + </style> </head> <body> - <div style="width:100%;"> - <canvas id="canvas" style="width:100%;height:100%"></canvas> - </div> - <br> - <br> - <button id="randomizeData">Randomize Data</button> - <button id="addDataset">Add Dataset</button> - <button id="removeDataset">Remove Dataset</button> - <button id="addData">Add Data</button> - <button id="removeData">Remove Data</button> - <div> - <h3>Legend</h3> - <div id="legendContainer"> - </div> - </div> - <script> - var randomScalingFactor = function() { - return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1)); - }; - var randomColorFactor = function() { - return Math.round(Math.random() * 255); - }; - var randomColor = function(opacity) { - return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')'; - }; - var newDate = function(days) { - var date = new Date(); - return date.setDate(date.getDate() + days); - }; - var newTimestamp = function(days) { - return Date.now() - days * 100000; - }; - - var config = { - type: 'bar', - data: { - //labels: [newTimestamp(0), newTimestamp(1), newTimestamp(2), newTimestamp(3), newTimestamp(4), newTimestamp(5), newTimestamp(6)], // unix timestamps - // labels: [newDate(0), newDate(1), newDate(2), newDate(3), newDate(4), newDate(5), newDate(6)], // Date Objects - labels: ["01/01/2015 20:00", "01/02/2015 20:00", "01/03/2015 22:00", "01/05/2015 23:00", "01/07/2015 03:00", "01/08/2015 10:00", "01/10/2015"], // Hours - // labels: ["01/01/2015", "01/02/2015", "01/03/2015", "01/06/2015", "01/15/2015", "01/17/2015", "01/30/2015"], // Days - // labels: ["12/25/2014", "01/08/2015", "01/15/2015", "01/22/2015", "01/29/2015", "02/05/2015", "02/12/2015"], // Weeks - datasets: [{ - type: 'bar', - label: 'Dataset 1', - backgroundColor: "rgba(151,187,205,0.5)", - data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], - borderColor: 'white', - borderWidth: 2 - }, { - type: 'bar', - label: 'Dataset 2', - backgroundColor: "rgba(151,187,205,0.5)", - data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], - borderColor: 'white', - borderWidth: 2 - }, { - type: 'line', - label: 'Dataset 3', - backgroundColor: "rgba(220,220,220,0.5)", - data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()] - }, ] - }, - options: { - responsive: true, - scales: { - xAxes: [{ - type: "time", - display: true, - time: { - format: 'MM/DD/YYYY HH:mm', - // round: 'day' - } - }, ], - yAxes: [{ - display: true - }] - }, - elements: { - line: { - tension: 0.3 - } - }, - } - }; - - $.each(config.data.datasets, function(i, dataset) { - dataset.borderColor = randomColor(0.4); - dataset.backgroundColor = randomColor(0.5); - dataset.pointBorderColor = randomColor(0.7); - dataset.pointBackgroundColor = randomColor(0.5); - dataset.pointBorderWidth = 1; - }); - - console.log(config.data); - - window.onload = function() { - var ctx = document.getElementById("canvas").getContext("2d"); - window.myLine = new Chart(ctx, config); - - updateLegend(); - }; - - function updateLegend() { - $legendContainer = $('#legendContainer'); - $legendContainer.empty(); - $legendContainer.append(window.myLine.generateLegend()); - } - - $('#randomizeData').click(function() { - $.each(config.data.datasets, function(i, dataset) { - dataset.data = dataset.data.map(function() { - return randomScalingFactor(); - }); - }); - - window.myLine.update(); - updateLegend(); - }); - - $('#addDataset').click(function() { - var newDataset = { - label: 'Dataset ' + config.data.datasets.length, - borderColor: randomColor(0.4), - backgroundColor: randomColor(0.5), - pointBorderColor: randomColor(0.7), - pointBackgroundColor: randomColor(0.5), - pointBorderWidth: 1, - data: [], - }; - - for (var index = 0; index < config.data.labels.length; ++index) { - newDataset.data.push(randomScalingFactor()); - } - - config.data.datasets.push(newDataset); - window.myLine.update(); - updateLegend(); - }); - - $('#addData').click(function() { - if (config.data.datasets.length > 0) { - config.data.labels.push( - myLine.scales['x-axis-0'].labelMoments[myLine.scales['x-axis-0'].labelMoments.length - 1].add(1, 'day') - .format('MM/DD/YYYY') - ); - - for (var index = 0; index < config.data.datasets.length; ++index) { - config.data.datasets[index].data.push(randomScalingFactor()); - } - - window.myLine.update(); - updateLegend(); - } - }); - - $('#removeDataset').click(function() { - config.data.datasets.splice(0, 1); - window.myLine.update(); - updateLegend(); - }); - - $('#removeData').click(function() { - config.data.labels.splice(-1, 1); // remove the label first - - config.data.datasets.forEach(function(dataset, datasetIndex) { - config.data.datasets[datasetIndex].data.pop(); - }); - - window.myLine.update(); - updateLegend(); - }); - </script> + <div style="width:100%;"> + <canvas id="canvas" style="width:100%;height:100%"></canvas> + </div> + <br> + <br> + <button id="randomizeData">Randomize Data</button> + <button id="addDataset">Add Dataset</button> + <button id="removeDataset">Remove Dataset</button> + <button id="addData">Add Data</button> + <button id="removeData">Remove Data</button> + <div> + <h3>Legend</h3> + <div id="legendContainer"> + </div> + </div> + <script> + var timeFormat = 'MM/DD/YYYY HH:mm'; + + function randomScalingFactor() { + return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1)); + } + + function randomColorFactor() { + return Math.round(Math.random() * 255); + } + + function randomColor(opacity) { + return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')'; + } + + function newDateString(days) { + return moment().add(days, 'd').format(timeFormat); + } + + var config = { + type: 'bar', + data: { + labels: [newDateString(0), newDateString(1), newDateString(2), newDateString(3), newDateString(4), newDateString(5), newDateString(6)], + datasets: [{ + type: 'bar', + label: 'Dataset 1', + backgroundColor: "rgba(151,187,205,0.5)", + data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], + borderColor: 'white', + borderWidth: 2 + }, { + type: 'bar', + label: 'Dataset 2', + backgroundColor: "rgba(151,187,205,0.5)", + data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], + borderColor: 'white', + borderWidth: 2 + }, { + type: 'line', + label: 'Dataset 3', + backgroundColor: "rgba(220,220,220,0.5)", + data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()] + }, ] + }, + options: { + responsive: true, + scales: { + xAxes: [{ + type: "time", + display: true, + time: { + format: timeFormat, + // round: 'day' + } + }], + }, + } + }; + + $.each(config.data.datasets, function(i, dataset) { + dataset.borderColor = randomColor(0.4); + dataset.backgroundColor = randomColor(0.5); + dataset.pointBorderColor = randomColor(0.7); + dataset.pointBackgroundColor = randomColor(0.5); + dataset.pointBorderWidth = 1; + }); + + console.log(config.data); + + window.onload = function() { + var ctx = document.getElementById("canvas").getContext("2d"); + window.myLine = new Chart(ctx, config); + + updateLegend(); + }; + + function updateLegend() { + $legendContainer = $('#legendContainer'); + $legendContainer.empty(); + $legendContainer.append(window.myLine.generateLegend()); + } + + $('#randomizeData').click(function() { + $.each(config.data.datasets, function(i, dataset) { + dataset.data = dataset.data.map(function() { + return randomScalingFactor(); + }); + }); + + window.myLine.update(); + updateLegend(); + }); + + $('#addDataset').click(function() { + var newDataset = { + label: 'Dataset ' + config.data.datasets.length, + borderColor: randomColor(0.4), + backgroundColor: randomColor(0.5), + pointBorderColor: randomColor(0.7), + pointBackgroundColor: randomColor(0.5), + pointBorderWidth: 1, + data: [], + }; + + for (var index = 0; index < config.data.labels.length; ++index) { + newDataset.data.push(randomScalingFactor()); + } + + config.data.datasets.push(newDataset); + window.myLine.update(); + updateLegend(); + }); + + $('#addData').click(function() { + if (config.data.datasets.length > 0) { + config.data.labels.push( + myLine.scales['x-axis-0'].labelMoments[myLine.scales['x-axis-0'].labelMoments.length - 1].add(1, 'day') + .format('MM/DD/YYYY') + ); + + for (var index = 0; index < config.data.datasets.length; ++index) { + config.data.datasets[index].data.push(randomScalingFactor()); + } + + window.myLine.update(); + updateLegend(); + } + }); + + $('#removeDataset').click(function() { + config.data.datasets.splice(0, 1); + window.myLine.update(); + updateLegend(); + }); + + $('#removeData').click(function() { + config.data.labels.splice(-1, 1); // remove the label first + + config.data.datasets.forEach(function(dataset, datasetIndex) { + config.data.datasets[datasetIndex].data.pop(); + }); + + window.myLine.update(); + updateLegend(); + }); + </script> </body> </html>
true
Other
chartjs
Chart.js
28fc6841f302d595fdf78f441c6e030fe815dc07.json
Add tooltipFormat option to time scale options. Fix bars when displayed on a time scale. Updated sample files.
samples/timeScale/line-time-point-data.html
@@ -2,163 +2,171 @@ <html> <head> - <title>Time Scale Point Data</title> - <script src="../node_modules/moment/min/moment.min.js"></script> - <script src="../Chart.js"></script> - <script src="../node_modules/jquery/dist/jquery.min.js"></script> - <style> - canvas { - -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, .5); - } - </style> + <title>Time Scale Point Data</title> + <script src="../../node_modules/moment/min/moment.min.js"></script> + <script src="../../Chart.js"></script> + <script src="../../node_modules/jquery/dist/jquery.min.js"></script> + <style> + canvas { + -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, .5); + } + </style> </head> <body> - <div style="width:100%;"> - <canvas id="canvas" style="width:100%;height:100%"></canvas> - </div> - <br> - <br> - <button id="randomizeData">Randomize Data</button> - <button id="addData">Add Data</button> - <button id="removeData">Remove Data</button> - <div> - <h3>Legend</h3> - <div id="legendContainer"> - </div> - </div> - <script> - var randomScalingFactor = function() { - return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1)); - }; - var randomColorFactor = function() { - return Math.round(Math.random() * 255); - }; - var randomColor = function(opacity) { - return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')'; - }; - var newDate = function(days) { - var date = new Date(); - return date.setDate(date.getDate() + days); - }; - var newTimestamp = function(days) { - return Date.now() - days * 100000; - }; - - var config = { - type: 'line', - data: { - datasets: [{ - label: "Dataset with point data", - data: [{ - x: "12/31/2014 06:00", - y: randomScalingFactor() - }, { - x: "01/04/2015 13:00", - y: randomScalingFactor() - }, { - x: "01/07/2015 01:15", - y: randomScalingFactor() - }, { - x: "01/15/2015 01:15", - y: randomScalingFactor() - }], - fill: false - }] - }, - options: { - responsive: true, - scales: { - xAxes: [{ - type: "time", - display: true, - time: { - format: 'MM/DD/YYYY HH:mm', - // round: 'day' - }, - scaleLabel: { - display: true, - labelString: 'Date' - } - }, ], - yAxes: [{ - display: true, - scaleLabel: { - display: true, - labelString: 'value' - } - }] - }, - elements: { - line: { - tension: 0.3 - } - }, - } - }; - - $.each(config.data.datasets, function(i, dataset) { - dataset.borderColor = randomColor(0.4); - dataset.backgroundColor = randomColor(0.5); - dataset.pointBorderColor = randomColor(0.7); - dataset.pointBackgroundColor = randomColor(0.5); - dataset.pointBorderWidth = 1; - }); - - console.log(config.data); - - window.onload = function() { - var ctx = document.getElementById("canvas").getContext("2d"); - window.myLine = new Chart(ctx, config); - - updateLegend(); - }; - - function updateLegend() { - $legendContainer = $('#legendContainer'); - $legendContainer.empty(); - $legendContainer.append(window.myLine.generateLegend()); - } - - $('#randomizeData').click(function() { - $.each(config.data.datasets, function(i, dataset) { - dataset.data = dataset.data.map(function() { - return randomScalingFactor(); - }); - }); - - window.myLine.update(); - updateLegend(); - }); - - $('#addData').click(function() { - if (config.data.datasets.length > 0) { - var newTime = myLine.scales['x-axis-0'].labelMoments[0][myLine.scales['x-axis-0'].labelMoments[0].length - 1] - .clone() - .add(1, 'day') - .format('MM/DD/YYYY HH:mm'); - - for (var index = 0; index < config.data.datasets.length; ++index) { - config.data.datasets[index].data.push({ - x: newTime, - y: randomScalingFactor() - }); - } - - window.myLine.update(); - updateLegend(); - } - }); - - $('#removeData').click(function() { - config.data.datasets.forEach(function(dataset, datasetIndex) { - dataset.data.pop(); - }); - - window.myLine.update(); - updateLegend(); - }); - </script> + <div style="width:100%;"> + <canvas id="canvas" style="width:100%;height:100%"></canvas> + </div> + <br> + <br> + <button id="randomizeData">Randomize Data</button> + <button id="addData">Add Data</button> + <button id="removeData">Remove Data</button> + <div> + <h3>Legend</h3> + <div id="legendContainer"> + </div> + </div> + <script> + function randomScalingFactor() { + return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1)); + } + + function randomColorFactor() { + return Math.round(Math.random() * 255); + } + + function randomColor(opacity) { + return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')'; + } + + function newDate(days) { + return moment().add(days, 'd').toDate(); + } + + function newDateString(days) { + return moment().add(days, 'd').format(); + } + + var config = { + type: 'line', + data: { + datasets: [{ + label: "Dataset with string point data", + data: [{ + x: newDateString(0), + y: randomScalingFactor() + }, { + x: newDateString(2), + y: randomScalingFactor() + }, { + x: newDateString(4), + y: randomScalingFactor() + }, { + x: newDateString(5), + y: randomScalingFactor() + }], + fill: false + }, { + label: "Dataset with date object point data", + data: [{ + x: newDate(0), + y: randomScalingFactor() + }, { + x: newDate(2), + y: randomScalingFactor() + }, { + x: newDate(4), + y: randomScalingFactor() + }, { + x: newDate(5), + y: randomScalingFactor() + }], + fill: false + }] + }, + options: { + responsive: true, + scales: { + xAxes: [{ + type: "time", + display: true, + scaleLabel: { + display: true, + labelString: 'Date' + } + }, ], + yAxes: [{ + display: true, + scaleLabel: { + display: true, + labelString: 'value' + } + }] + } + } + }; + + $.each(config.data.datasets, function(i, dataset) { + dataset.borderColor = randomColor(0.4); + dataset.backgroundColor = randomColor(0.5); + dataset.pointBorderColor = randomColor(0.7); + dataset.pointBackgroundColor = randomColor(0.5); + dataset.pointBorderWidth = 1; + }); + + window.onload = function() { + var ctx = document.getElementById("canvas").getContext("2d"); + window.myLine = new Chart(ctx, config); + + updateLegend(); + }; + + function updateLegend() { + $legendContainer = $('#legendContainer'); + $legendContainer.empty(); + $legendContainer.append(window.myLine.generateLegend()); + } + + $('#randomizeData').click(function() { + $.each(config.data.datasets, function(i, dataset) { + $.each(dataset.data, function(j, dataObj) { + dataObj.y = randomScalingFactor(); + }); + }); + + window.myLine.update(); + updateLegend(); + }); + + $('#addData').click(function() { + if (config.data.datasets.length > 0) { + var newTime = myLine.scales['x-axis-0'].labelMoments[0][myLine.scales['x-axis-0'].labelMoments[0].length - 1] + .clone() + .add(1, 'day') + .format('MM/DD/YYYY HH:mm'); + + for (var index = 0; index < config.data.datasets.length; ++index) { + config.data.datasets[index].data.push({ + x: newTime, + y: randomScalingFactor() + }); + } + + window.myLine.update(); + updateLegend(); + } + }); + + $('#removeData').click(function() { + config.data.datasets.forEach(function(dataset, datasetIndex) { + dataset.data.pop(); + }); + + window.myLine.update(); + updateLegend(); + }); + </script> </body> </html>
true
Other
chartjs
Chart.js
28fc6841f302d595fdf78f441c6e030fe815dc07.json
Add tooltipFormat option to time scale options. Fix bars when displayed on a time scale. Updated sample files.
samples/timeScale/line-time-scale.html
@@ -2,205 +2,210 @@ <html> <head> - <title>Line Chart</title> - <script src="../node_modules/moment/min/moment.min.js"></script> - <script src="../Chart.js"></script> - <script src="../node_modules/jquery/dist/jquery.min.js"></script> - <style> - canvas { - -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, .5); - } - </style> + <title>Line Chart</title> + <script src="../../node_modules/moment/min/moment.min.js"></script> + <script src="../../Chart.js"></script> + <script src="../../node_modules/jquery/dist/jquery.min.js"></script> + <style> + canvas { + -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, .5); + } + </style> </head> <body> - <div style="width:100%;"> - <canvas id="canvas" style="width:100%;height:100%"></canvas> - </div> - <br> - <br> - <button id="randomizeData">Randomize Data</button> - <button id="addDataset">Add Dataset</button> - <button id="removeDataset">Remove Dataset</button> - <button id="addData">Add Data</button> - <button id="removeData">Remove Data</button> - <div> - <h3>Legend</h3> - <div id="legendContainer"> - </div> - </div> - <script> - var randomScalingFactor = function() { - return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1)); - }; - var randomColorFactor = function() { - return Math.round(Math.random() * 255); - }; - var randomColor = function(opacity) { - return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')'; - }; - var newDate = function(days) { - var date = new Date(); - return date.setDate(date.getDate() + days); - }; - var newTimestamp = function(days) { - return Date.now() - days * 100000; - }; - - var config = { - type: 'line', - data: { - //labels: [newTimestamp(0), newTimestamp(1), newTimestamp(2), newTimestamp(3), newTimestamp(4), newTimestamp(5), newTimestamp(6)], // unix timestamps - // labels: [newDate(0), newDate(1), newDate(2), newDate(3), newDate(4), newDate(5), newDate(6)], // Date Objects - labels: ["01/01/2015 20:00", "01/02/2015 21:00", "01/03/2015 22:00", "01/05/2015 23:00", "01/07/2015 03:00", "01/08/2015 10:00", "01/10/2015"], // Hours - // labels: ["01/01/2015", "01/02/2015", "01/03/2015", "01/06/2015", "01/15/2015", "01/17/2015", "01/30/2015"], // Days - // labels: ["12/25/2014", "01/08/2015", "01/15/2015", "01/22/2015", "01/29/2015", "02/05/2015", "02/12/2015"], // Weeks - datasets: [{ - label: "My First dataset", - data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], - fill: false, - borderDash: [5, 5], - }, { - label: "My Second dataset", - data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], - }, { - label: "Dataset with point data", - data: [{ - x: "12/31/2014 06:00", - y: randomScalingFactor() - }, { - x: "01/04/2015 13:00", - y: randomScalingFactor() - }, { - x: "01/07/2015 01:15", - y: randomScalingFactor() - }, { - x: "01/15/2015 01:15", - y: randomScalingFactor() - }], - fill: false - }] - }, - options: { - responsive: true, - scales: { - xAxes: [{ - type: "time", - display: true, - time: { - format: 'MM/DD/YYYY HH:mm', - // round: 'day' - }, - scaleLabel: { - display: true, - labelString: 'Date' - } - }, ], - yAxes: [{ - display: true, - scaleLabel: { - display: true, - labelString: 'value' - } - }] - }, - elements: { - line: { - tension: 0.3 - } - }, - } - }; - - $.each(config.data.datasets, function(i, dataset) { - dataset.borderColor = randomColor(0.4); - dataset.backgroundColor = randomColor(0.5); - dataset.pointBorderColor = randomColor(0.7); - dataset.pointBackgroundColor = randomColor(0.5); - dataset.pointBorderWidth = 1; - }); - - console.log(config.data); - - window.onload = function() { - var ctx = document.getElementById("canvas").getContext("2d"); - window.myLine = new Chart(ctx, config); - - updateLegend(); - }; - - function updateLegend() { - $legendContainer = $('#legendContainer'); - $legendContainer.empty(); - $legendContainer.append(window.myLine.generateLegend()); - } - - $('#randomizeData').click(function() { - $.each(config.data.datasets, function(i, dataset) { - dataset.data = dataset.data.map(function() { - return randomScalingFactor(); - }); - }); - - window.myLine.update(); - updateLegend(); - }); - - $('#addDataset').click(function() { - var newDataset = { - label: 'Dataset ' + config.data.datasets.length, - borderColor: randomColor(0.4), - backgroundColor: randomColor(0.5), - pointBorderColor: randomColor(0.7), - pointBackgroundColor: randomColor(0.5), - pointBorderWidth: 1, - data: [], - }; - - for (var index = 0; index < config.data.labels.length; ++index) { - newDataset.data.push(randomScalingFactor()); - } - - config.data.datasets.push(newDataset); - window.myLine.update(); - updateLegend(); - }); - - $('#addData').click(function() { - if (config.data.datasets.length > 0) { - config.data.labels.push( - myLine.scales['x-axis-0'].labelMoments[myLine.scales['x-axis-0'].labelMoments.length - 1] - .clone() - .add(1, 'day') - .format('MM/DD/YYYY HH:mm') - ); - - for (var index = 0; index < config.data.datasets.length; ++index) { - config.data.datasets[index].data.push(randomScalingFactor()); - } - - window.myLine.update(); - updateLegend(); - } - }); - - $('#removeDataset').click(function() { - config.data.datasets.splice(0, 1); - window.myLine.update(); - updateLegend(); - }); - - $('#removeData').click(function() { - config.data.labels.splice(-1, 1); // remove the label first - - config.data.datasets.forEach(function(dataset, datasetIndex) { - dataset.data.pop(); - }); - - window.myLine.update(); - updateLegend(); - }); - </script> + <div style="width:100%;"> + <canvas id="canvas" style="width:100%;height:100%"></canvas> + </div> + <br> + <br> + <button id="randomizeData">Randomize Data</button> + <button id="addDataset">Add Dataset</button> + <button id="removeDataset">Remove Dataset</button> + <button id="addData">Add Data</button> + <button id="removeData">Remove Data</button> + <div> + <h3>Legend</h3> + <div id="legendContainer"> + </div> + </div> + <script> + var timeFormat = 'MM/DD/YYYY HH:mm'; + + function randomScalingFactor() { + return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1)); + } + + function randomColorFactor() { + return Math.round(Math.random() * 255); + } + + function randomColor(opacity) { + return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')'; + } + + function newDate(days) { + return moment().add(days, 'd').toDate(); + } + + function newDateString(days) { + return moment().add(days, 'd').format(timeFormat); + } + + function newTimestamp(days) { + return moment().add(days, 'd').unix(); + } + + var config = { + type: 'line', + data: { + labels: [newDate(0), newDate(1), newDate(2), newDate(3), newDate(4), newDate(5), newDate(6)], // Date Objects + datasets: [{ + label: "My First dataset", + data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], + fill: false, + borderDash: [5, 5], + }, { + label: "My Second dataset", + data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], + }, { + label: "Dataset with point data", + data: [{ + x: newDateString(0), + y: randomScalingFactor() + }, { + x: newDateString(5), + y: randomScalingFactor() + }, { + x: newDateString(7), + y: randomScalingFactor() + }, { + x: newDateString(15), + y: randomScalingFactor() + }], + fill: false + }] + }, + options: { + responsive: true, + scales: { + xAxes: [{ + type: "time", + time: { + format: timeFormat, + // round: 'day' + tooltipFormat: 'll HH:mm' + }, + scaleLabel: { + display: true, + labelString: 'Date' + } + }, ], + yAxes: [{ + scaleLabel: { + display: true, + labelString: 'value' + } + }] + }, + } + }; + + $.each(config.data.datasets, function(i, dataset) { + dataset.borderColor = randomColor(0.4); + dataset.backgroundColor = randomColor(0.5); + dataset.pointBorderColor = randomColor(0.7); + dataset.pointBackgroundColor = randomColor(0.5); + dataset.pointBorderWidth = 1; + }); + + console.log(config.data); + + window.onload = function() { + var ctx = document.getElementById("canvas").getContext("2d"); + window.myLine = new Chart(ctx, config); + + updateLegend(); + }; + + function updateLegend() { + $legendContainer = $('#legendContainer'); + $legendContainer.empty(); + $legendContainer.append(window.myLine.generateLegend()); + } + + $('#randomizeData').click(function() { + $.each(config.data.datasets, function(i, dataset) { + $.each(dataset.data, function(j, dataObj) { + if (typeof dataObj === 'object') { + dataObj.y = randomScalingFactor(); + } else { + dataset.data[j] = randomScalingFactor(); + } + }); + }); + + window.myLine.update(); + updateLegend(); + }); + + $('#addDataset').click(function() { + var newDataset = { + label: 'Dataset ' + config.data.datasets.length, + borderColor: randomColor(0.4), + backgroundColor: randomColor(0.5), + pointBorderColor: randomColor(0.7), + pointBackgroundColor: randomColor(0.5), + pointBorderWidth: 1, + data: [], + }; + + for (var index = 0; index < config.data.labels.length; ++index) { + newDataset.data.push(randomScalingFactor()); + } + + config.data.datasets.push(newDataset); + window.myLine.update(); + updateLegend(); + }); + + $('#addData').click(function() { + if (config.data.datasets.length > 0) { + config.data.labels.push(newDate(config.data.labels.length)); + + for (var index = 0; index < config.data.datasets.length; ++index) { + if (typeof config.data.datasets[index].data[0] === "object") { + config.data.datasets[index].data.push({ + x: newDate(config.data.datasets[index].data.length), + y: randomScalingFactor(), + }) + } else { + config.data.datasets[index].data.push(randomScalingFactor()); + } + } + + window.myLine.update(); + updateLegend(); + } + }); + + $('#removeDataset').click(function() { + config.data.datasets.splice(0, 1); + window.myLine.update(); + updateLegend(); + }); + + $('#removeData').click(function() { + config.data.labels.splice(-1, 1); // remove the label first + + config.data.datasets.forEach(function(dataset, datasetIndex) { + dataset.data.pop(); + }); + + window.myLine.update(); + updateLegend(); + }); + </script> </body> </html>
true
Other
chartjs
Chart.js
28fc6841f302d595fdf78f441c6e030fe815dc07.json
Add tooltipFormat option to time scale options. Fix bars when displayed on a time scale. Updated sample files.
src/controllers/controller.bar.js
@@ -233,9 +233,9 @@ var datasetCount = this.getBarCount(); var tickWidth = (function() { - var min = xScale.getPixelForValue(null, 1) - xScale.getPixelForValue(null, 0); + var min = xScale.getPixelForTick(1) - xScale.getPixelForTick(0); for (var i = 2; i < this.getDataset().data.length; i++) { - min = Math.min(xScale.getPixelForValue(null, i) - xScale.getPixelForValue(null, i - 1), min); + min = Math.min(xScale.getPixelForTick(i) - xScale.getPixelForTick(i - 1), min); } return min; }).call(this); @@ -290,7 +290,7 @@ var barIndex = this.getBarIndex(datasetIndex); var ruler = this.getRuler(); - var leftTick = xScale.getPixelForValue(null, index, barIndex, this.chart.isCombo); + var leftTick = xScale.getPixelForValue(null, index, datasetIndex, this.chart.isCombo); leftTick -= this.chart.isCombo ? (ruler.tickWidth / 2) : 0; if (xScale.options.stacked) {
true
Other
chartjs
Chart.js
28fc6841f302d595fdf78f441c6e030fe815dc07.json
Add tooltipFormat option to time scale options. Fix bars when displayed on a time scale. Updated sample files.
src/core/core.scale.js
@@ -334,7 +334,11 @@ } // If it is in fact an object, dive in one more level if (typeof(rawValue) === "object") { - return getRightValue(this.isHorizontal() ? rawValue.x : rawValue.y); + if (rawValue instanceof Date) { + return rawValue; + } else { + return getRightValue(this.isHorizontal() ? rawValue.x : rawValue.y); + } } // Value is good, return it
true
Other
chartjs
Chart.js
28fc6841f302d595fdf78f441c6e030fe815dc07.json
Add tooltipFormat option to time scale options. Fix bars when displayed on a time scale. Updated sample files.
src/scales/scale.time.js
@@ -164,9 +164,9 @@ if (helpers.isArray(unitDefinition.steps) && Math.ceil(this.tickRange / labelCapacity) < helpers.max(unitDefinition.steps)) { // Use one of the prefedined steps - for (var idx = 1; idx < unitDefinition.steps.length; ++idx) { + for (var idx = 0; idx < unitDefinition.steps.length; ++idx) { if (unitDefinition.steps[idx] > Math.ceil(this.tickRange / labelCapacity)) { - this.unitScale = unitDefinition.steps[idx - 1]; + this.unitScale = unitDefinition.steps[idx]; break; } } @@ -224,11 +224,16 @@ label = this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); } + // Format nicely + if (this.options.time.tooltipFormat) { + label = this.parseTime(label).format(this.options.time.tooltipFormat); + } + return label; }, convertTicksToLabels: function() { this.ticks = this.ticks.map(function(tick, index, ticks) { - var formattedTick = tick.format(this.options.time.displayFormat ? this.options.time.displayFormat : this.options.time.displayFormats[this.tickUnit]); + var formattedTick = tick.format(this.displayFormat); if (this.options.ticks.userCallback) { return this.options.ticks.userCallback(formattedTick, index, ticks); @@ -250,7 +255,6 @@ return this.left + Math.round(valueOffset); } else { - //return this.top + (decimal * (this.height / this.ticks.length)); var innerHeight = this.height - (this.paddingTop + this.paddingBottom); var valueHeight = innerHeight / Math.max(this.ticks.length - 1, 1); var heightOffset = (innerHeight * decimal) + this.paddingTop;
true
Other
chartjs
Chart.js
28fc6841f302d595fdf78f441c6e030fe815dc07.json
Add tooltipFormat option to time scale options. Fix bars when displayed on a time scale. Updated sample files.
test/scale.time.tests.js
@@ -92,7 +92,35 @@ describe('Time scale tests', function() { scale.update(400, 50); // Counts down because the lines are drawn top to bottom - expect(scale.ticks).toEqual(['Jan 1, 2015', 'Jan 2, 2015', 'Jan 3, 2015', 'Jan 4, 2015', 'Jan 5, 2015', 'Jan 6, 2015', 'Jan 7, 2015', 'Jan 8, 2015', 'Jan 9, 2015', 'Jan 10, 2015', 'Jan 11, 2015']); + expect(scale.ticks).toEqual(['Jan 1, 2015', 'Jan 3, 2015', 'Jan 5, 2015', 'Jan 7, 2015', 'Jan 9, 2015', 'Jan 11, 2015']); + }); + + it('should build ticks using date objects', function() { + // Helper to build date objects + function newDateFromRef(days) { + return moment('01/01/2015 12:00', 'DD/MM/YYYY HH:mm').add(days, 'd').toDate(); + } + + var scaleID = 'myScale'; + var mockData = { + labels: [newDateFromRef(0), newDateFromRef(1), newDateFromRef(2), newDateFromRef(4), newDateFromRef(6), newDateFromRef(7), newDateFromRef(9)], // days + }; + + var mockContext = window.createMockContext(); + var Constructor = Chart.scaleService.getScaleConstructor('time'); + var scale = new Constructor({ + ctx: mockContext, + options: Chart.scaleService.getScaleDefaults('time'), // use default config for scale + chart: { + data: mockData + }, + id: scaleID + }); + + scale.update(400, 50); + + // Counts down because the lines are drawn top to bottom + expect(scale.ticks).toEqual(['Jan 1, 2015', 'Jan 3, 2015', 'Jan 5, 2015', 'Jan 7, 2015', 'Jan 9, 2015', 'Jan 11, 2015', 'Jan 13, 2015']); }); it('should build ticks using the config unit', function() {
true
Other
chartjs
Chart.js
d8704ee37ded3d81c5ea747c5b181357f5fe209b.json
Add legends to sample files
samples/bar.html
@@ -70,6 +70,13 @@ <h3>Legend</h3> data: barChartData, options: { responsive: true, + legend: { + position: 'top', + title: { + display: true, + text: 'Our 3 Favorite Datasets' + } + }, } });
true
Other
chartjs
Chart.js
d8704ee37ded3d81c5ea747c5b181357f5fe209b.json
Add legends to sample files
samples/doughnut.html
@@ -101,7 +101,14 @@ <h3>Legend</h3> ] }, options: { - responsive: true + responsive: true, + legend: { + position: 'top', + title: { + display: true, + text: 'Our 2 Favorite Datasets' + } + }, } };
true
Other
chartjs
Chart.js
d8704ee37ded3d81c5ea747c5b181357f5fe209b.json
Add legends to sample files
samples/polar-area.html
@@ -59,6 +59,13 @@ <h3>Legend</h3> }, options: { responsive: true, + legend: { + position: 'top', + title: { + display: true, + text: 'Our Favorite Dataset' + } + }, scale: { ticks: { beginAtZero: true
true
Other
chartjs
Chart.js
d8704ee37ded3d81c5ea747c5b181357f5fe209b.json
Add legends to sample files
samples/radar.html
@@ -56,6 +56,13 @@ <h3>Legend</h3> },] }, options: { + legend: { + position: 'top', + title: { + display: true, + text: 'Our 3 Favorite Datasets' + } + }, scale: { reverse: true, ticks: {
true
Other
chartjs
Chart.js
0b260d57cce124597d2f4186629a1409c98f8da5.json
Fix JSHint issue
src/core/core.controller.js
@@ -422,7 +422,7 @@ } else { var _this = this; - function getItemsForMode(mode) { + var getItemsForMode = function(mode) { switch (mode) { case 'single': return _this.getElementAtEvent(e); @@ -433,7 +433,7 @@ default: return e; } - } + }; this.active = getItemsForMode(this.options.hover.mode); this.tooltipActive = getItemsForMode(this.options.tooltips.mode);
false
Other
chartjs
Chart.js
0ed39c9fd702a0f281206137b01131080be8712b.json
Fix error in math helpers.
src/core/core.helpers.js
@@ -271,7 +271,7 @@ } else { return max; } - }, Number.MIN_VALUE); + }, Number.NEGATIVE_INFINITY); }; helpers.min = function(array) { return array.reduce(function(min, value) { @@ -280,7 +280,7 @@ } else { return min; } - }, Number.MAX_VALUE); + }, Number.POSITIVE_INFINITY); }; helpers.sign = function(x) { if (Math.sign) {
false
Other
chartjs
Chart.js
24e4a924c4b6adcb787e13eb417b3e1845e9cf11.json
Add option to disable line drawing
docs/02-Line-Chart.md
@@ -120,6 +120,7 @@ The default options for line chart are defined in `Chart.defaults.Line`. Name | Type | Default | Description --- | --- | --- | --- +showLines | Boolean | true | If false, the lines between points are not drawn stacked | Boolean | false | If true, lines stack on top of each other along the y axis. *hover*.mode | String | "label" | Label's hover mode. "label" is used since the x axis displays data by the index in the dataset. scales | - | - | -
true
Other
chartjs
Chart.js
24e4a924c4b6adcb787e13eb417b3e1845e9cf11.json
Add option to disable line drawing
src/controllers/controller.line.js
@@ -7,6 +7,8 @@ helpers = Chart.helpers; Chart.defaults.line = { + showLines: true, + hover: { mode: "label" }, @@ -58,7 +60,8 @@ this.getDataset().metaData.splice(index, 0, point); // Make sure bezier control points are updated - this.updateBezierControlPoints(); + if (this.chart.options.showLines) + this.updateBezierControlPoints(); }, update: function update(reset) { @@ -78,38 +81,41 @@ } // Update Line - helpers.extend(line, { - // Utility - _scale: yScale, - _datasetIndex: this.index, - // Data - _children: points, - // Model - _model: { - // Appearance - tension: line.custom && line.custom.tension ? line.custom.tension : helpers.getValueOrDefault(this.getDataset().tension, this.chart.options.elements.line.tension), - backgroundColor: line.custom && line.custom.backgroundColor ? line.custom.backgroundColor : (this.getDataset().backgroundColor || this.chart.options.elements.line.backgroundColor), - borderWidth: line.custom && line.custom.borderWidth ? line.custom.borderWidth : (this.getDataset().borderWidth || this.chart.options.elements.line.borderWidth), - borderColor: line.custom && line.custom.borderColor ? line.custom.borderColor : (this.getDataset().borderColor || this.chart.options.elements.line.borderColor), - borderCapStyle: line.custom && line.custom.borderCapStyle ? line.custom.borderCapStyle : (this.getDataset().borderCapStyle || this.chart.options.elements.line.borderCapStyle), - borderDash: line.custom && line.custom.borderDash ? line.custom.borderDash : (this.getDataset().borderDash || this.chart.options.elements.line.borderDash), - borderDashOffset: line.custom && line.custom.borderDashOffset ? line.custom.borderDashOffset : (this.getDataset().borderDashOffset || this.chart.options.elements.line.borderDashOffset), - borderJoinStyle: line.custom && line.custom.borderJoinStyle ? line.custom.borderJoinStyle : (this.getDataset().borderJoinStyle || this.chart.options.elements.line.borderJoinStyle), - fill: line.custom && line.custom.fill ? line.custom.fill : (this.getDataset().fill !== undefined ? this.getDataset().fill : this.chart.options.elements.line.fill), - // Scale - scaleTop: yScale.top, - scaleBottom: yScale.bottom, - scaleZero: scaleBase, - }, - }); - line.pivot(); + if (this.chart.options.showLines) { + helpers.extend(line, { + // Utility + _scale: yScale, + _datasetIndex: this.index, + // Data + _children: points, + // Model + _model: { + // Appearance + tension: line.custom && line.custom.tension ? line.custom.tension : helpers.getValueOrDefault(this.getDataset().tension, this.chart.options.elements.line.tension), + backgroundColor: line.custom && line.custom.backgroundColor ? line.custom.backgroundColor : (this.getDataset().backgroundColor || this.chart.options.elements.line.backgroundColor), + borderWidth: line.custom && line.custom.borderWidth ? line.custom.borderWidth : (this.getDataset().borderWidth || this.chart.options.elements.line.borderWidth), + borderColor: line.custom && line.custom.borderColor ? line.custom.borderColor : (this.getDataset().borderColor || this.chart.options.elements.line.borderColor), + borderCapStyle: line.custom && line.custom.borderCapStyle ? line.custom.borderCapStyle : (this.getDataset().borderCapStyle || this.chart.options.elements.line.borderCapStyle), + borderDash: line.custom && line.custom.borderDash ? line.custom.borderDash : (this.getDataset().borderDash || this.chart.options.elements.line.borderDash), + borderDashOffset: line.custom && line.custom.borderDashOffset ? line.custom.borderDashOffset : (this.getDataset().borderDashOffset || this.chart.options.elements.line.borderDashOffset), + borderJoinStyle: line.custom && line.custom.borderJoinStyle ? line.custom.borderJoinStyle : (this.getDataset().borderJoinStyle || this.chart.options.elements.line.borderJoinStyle), + fill: line.custom && line.custom.fill ? line.custom.fill : (this.getDataset().fill !== undefined ? this.getDataset().fill : this.chart.options.elements.line.fill), + // Scale + scaleTop: yScale.top, + scaleBottom: yScale.bottom, + scaleZero: scaleBase, + }, + }); + line.pivot(); + } // Update Points helpers.each(points, function(point, index) { this.updateElement(point, index, reset); }, this); - this.updateBezierControlPoints(); + if (this.chart.options.showLines) + this.updateBezierControlPoints(); }, getPointBackgroundColor: function(point, index) { @@ -258,7 +264,8 @@ }, this); // Transition and Draw the line - this.getDataset().metaDataset.transition(easingDecimal).draw(); + if (this.chart.options.showLines) + this.getDataset().metaDataset.transition(easingDecimal).draw(); // Draw the points helpers.each(this.getDataset().metaData, function(point) {
true
Other
chartjs
Chart.js
24e4a924c4b6adcb787e13eb417b3e1845e9cf11.json
Add option to disable line drawing
test/controller.line.tests.js
@@ -87,6 +87,7 @@ describe('Line controller tests', function() { type: 'line' }, options: { + showLines: true, scales: { xAxes: [{ id: 'firstXScaleID' @@ -114,6 +115,45 @@ describe('Line controller tests', function() { expect(chart.data.datasets[0].metaData[3].draw.calls.count()).toBe(1); }); + it('should draw all elements except lines', function() { + var chart = { + data: { + datasets: [{ + data: [10, 15, 0, -4] + }] + }, + config: { + type: 'line' + }, + options: { + showLines: false, + scales: { + xAxes: [{ + id: 'firstXScaleID' + }], + yAxes: [{ + id: 'firstYScaleID' + }] + } + } + }; + + var controller = new Chart.controllers.line(chart, 0); + + spyOn(chart.data.datasets[0].metaDataset, 'draw'); + spyOn(chart.data.datasets[0].metaData[0], 'draw'); + spyOn(chart.data.datasets[0].metaData[1], 'draw'); + spyOn(chart.data.datasets[0].metaData[2], 'draw'); + spyOn(chart.data.datasets[0].metaData[3], 'draw'); + + controller.draw(); + + expect(chart.data.datasets[0].metaDataset.draw.calls.count()).toBe(0); + expect(chart.data.datasets[0].metaData[0].draw.calls.count()).toBe(1); + expect(chart.data.datasets[0].metaData[2].draw.calls.count()).toBe(1); + expect(chart.data.datasets[0].metaData[3].draw.calls.count()).toBe(1); + }); + it('should update elements', function() { var data = { datasets: [{ @@ -177,6 +217,7 @@ describe('Line controller tests', function() { type: 'line' }, options: { + showLines: true, elements: { line: { backgroundColor: 'rgb(255, 0, 0)',
true
Other
chartjs
Chart.js
977d45a3e09393efbbdd2089e6e473f11c7f514b.json
Add some optimizations to often used functions
src/core/core.helpers.js
@@ -11,25 +11,25 @@ //-- Basic js utility methods helpers.each = function(loopable, callback, self, reverse) { - var additionalArgs = Array.prototype.slice.call(arguments, 3); // Check to see if null or undefined firstly. - if (loopable) { - if (loopable.length === +loopable.length) { - var i; - if (reverse) { - for (i = loopable.length - 1; i >= 0; i--) { - callback.apply(self, [loopable[i], i].concat(additionalArgs)); - } - } else { - for (i = 0; i < loopable.length; i++) { - callback.apply(self, [loopable[i], i].concat(additionalArgs)); - } + var i, len; + if (helpers.isArray(loopable)) { + len = loopable.length; + if (reverse) { + for (i = len - 1; i >= 0; i--) { + callback.call(self, loopable[i], i); } } else { - for (var item in loopable) { - callback.apply(self, [loopable[item], item].concat(additionalArgs)); + for (i = 0; i < len; i++) { + callback.call(self, loopable[i], i); } } + } else if (typeof loopable === 'object') { + var keys = Object.keys(loopable); + len = keys.length; + for (i = 0; i < len; i++) { + callback.call(self, loopable[keys[i]], keys[i]); + } } }; helpers.clone = function(obj) { @@ -48,7 +48,12 @@ return objClone; }; helpers.extend = function(base) { - helpers.each(Array.prototype.slice.call(arguments, 1), function(extensionObject) { + var len = arguments.length; + var additionalArgs = []; + for(var i = 1; i < len; i++) { + additionalArgs.push(arguments[i]); + } + helpers.each(additionalArgs, function(extensionObject) { helpers.each(extensionObject, function(value, key) { if (extensionObject.hasOwnProperty(key)) { base[key] = value;
false
Other
chartjs
Chart.js
88fc6ecc5c5b7ed3c36e9baca74e9fbfa48a17c5.json
Fix orf/olf being undefined
src/core/core.tooltip.js
@@ -362,13 +362,14 @@ if (this._model.yAlign === 'center') { lf = function(x) { return x <= midX; }; rf = function(x) { return x > midX; }; - olf = function(x) { return x + size.width > _this._chart.width; }; - orf = function(x) { return x - size.width < 0; }; - yf = function(y) { return y <= midY ? 'top' : 'bottom'; }; } else { lf = function(x) { return x <= (size.width / 2); }; rf = function(x) { return x >= (_this._chart.width - (size.width / 2)); }; } + + olf = function(x) { return x + size.width > _this._chart.width; }; + orf = function(x) { return x - size.width < 0; }; + yf = function(y) { return y <= midY ? 'top' : 'bottom'; }; if (lf(this._model.x)) { this._model.xAlign = 'left';
false
Other
chartjs
Chart.js
d49b5b82c7d2f487cd858af278801aee3a564afe.json
Add test for scale
test/scale.linear.tests.js
@@ -321,6 +321,47 @@ describe('Linear Scale', function() { expect(scale.max).toBe(200); }); + it('Should correctly determine the min and max data values when stacked mode is turned on there are multiple types of datasets', function() { + var scaleID = 'myScale'; + + var mockData = { + datasets: [{ + type: 'bar', + yAxisID: scaleID, + data: [10, 5, 0, -5, 78, -100] + }, { + type: 'line', + yAxisID: scaleID, + data: [10, 10, 10, 10, 10, 10], + }, { + type: 'bar', + yAxisID: scaleID, + data: [150, 0, 0, -100, -10, 9] + }] + }; + + var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('linear')); + config.stacked = true; // enable scale stacked mode + + var Constructor = Chart.scaleService.getScaleConstructor('linear'); + var scale = new Constructor({ + ctx: {}, + options: config, + chart: { + data: mockData + }, + id: scaleID + }); + + // Set arbitrary width and height for now + scale.width = 50; + scale.height = 400; + + scale.determineDataLimits(); + expect(scale.min).toBe(-105); + expect(scale.max).toBe(160); + }); + it('Should ensure that the scale has a max and min that are not equal', function() { var scaleID = 'myScale';
false
Other
chartjs
Chart.js
57bd8c7715998a668d1a3b41daa8a520070969fe.json
Ignore null values when calculating scale
src/Chart.Core.js
@@ -409,8 +409,13 @@ maxSteps = Math.floor(drawingSize/(textSize * 1.5)), skipFitting = (minSteps >= maxSteps); - var maxValue = max(valuesArray), - minValue = min(valuesArray); + // Filter out null values since these would min() to zero + var values = []; + each(valuesArray, function( v ){ + v == null || values.push( v ); + }); + var minValue = min(values), + maxValue = max(values); // We need some degree of separation here to calculate the scales if all the values are the same // Adding/minusing 0.5 will give us a range of 1.
false
Other
chartjs
Chart.js
8487375730a0c932792a6b8b52922cfc875771ac.json
Update readme to latest beta version
README.md
@@ -7,7 +7,7 @@ ## v2.0 Beta -Current Release: [2.0.0-beta](https://github.com/nnnick/Chart.js/releases/tag/2.0.0-beta) +Current Release: [2.0.0-beta2](https://github.com/nnnick/Chart.js/releases/tag/2.0.0-beta2) The next generation and release of Chart.js has been well under way this year and we are very close to releasing some amazing new features including, but not limited to: - Rewritten, optimized, and unit-tested
false
Other
chartjs
Chart.js
fa6be2f772793525a9b2d68a58e5a6c9d31f426c.json
Fix inconsistent aspect ratio
src/controllers/controller.doughnut.js
@@ -12,7 +12,6 @@ module.exports = function(Chart) { // Boolean - Whether we animate scaling the Doughnut from the centre animateScale: false }, - aspectRatio: 1, hover: { mode: 'single' },
true
Other
chartjs
Chart.js
fa6be2f772793525a9b2d68a58e5a6c9d31f426c.json
Fix inconsistent aspect ratio
src/controllers/controller.polarArea.js
@@ -29,7 +29,6 @@ module.exports = function(Chart) { }, startAngle: -0.5 * Math.PI, - aspectRatio: 1, legendCallback: function(chart) { var text = []; text.push('<ul class="' + chart.id + '-legend">');
true
Other
chartjs
Chart.js
fa6be2f772793525a9b2d68a58e5a6c9d31f426c.json
Fix inconsistent aspect ratio
src/controllers/controller.radar.js
@@ -5,7 +5,6 @@ module.exports = function(Chart) { var helpers = Chart.helpers; Chart.defaults.radar = { - aspectRatio: 1, scale: { type: 'radialLinear' },
true
Other
chartjs
Chart.js
fa6be2f772793525a9b2d68a58e5a6c9d31f426c.json
Fix inconsistent aspect ratio
test/specs/platform.dom.tests.js
@@ -122,6 +122,9 @@ describe('Platform.dom', function() { }); it('should use default "chart" aspect ratio for render and display sizes', function() { + var ratio = Chart.defaults.doughnut.aspectRatio; + Chart.defaults.doughnut.aspectRatio = 1; + var chart = acquireChart({ type: 'doughnut', options: { @@ -133,6 +136,8 @@ describe('Platform.dom', function() { } }); + Chart.defaults.doughnut.aspectRatio = ratio; + expect(chart).toBeChartOfSize({ dw: 425, dh: 425, rw: 425, rh: 425,
true
Other
chartjs
Chart.js
0075373bec751f681253355ad5237da68f129405.json
Add GA tracking code to docs
book.json
@@ -2,13 +2,17 @@ "root": "./docs", "author": "chartjs", "gitbook": "3.2.2", - "plugins": ["-lunr", "-search", "search-plus", "anchorjs", "chartjs"], + "plugins": ["-lunr", "-search", "search-plus", "anchorjs", "chartjs", "ga"], "pluginsConfig": { "anchorjs": { "icon": "#", "placement": "left", "visible": "always" }, + "ga": { + "token": "UA-28909194-3", + "configuration": "auto" + }, "theme-default": { "showLevel": false, "styles": {
false
Other
chartjs
Chart.js
20452ddb7c7569c87b4379b1940a0efd5e4a5043.json
Fix invalid link in area.md (#4257)
docs/charts/area.md
@@ -2,7 +2,7 @@ Both [line](line.md) and [radar](radar.md) charts support a `fill` option on the dataset object which can be used to create area between two datasets or a dataset and a boundary, i.e. the scale `origin`, `start` or `end` (see [filling modes](#filling-modes)). -> **Note:** this feature is implemented by the [`filler` plugin](/chartjs/Chart.js/blob/master/src/plugins/plugin.filler.js). +> **Note:** this feature is implemented by the [`filler` plugin](https://github.com/chartjs/Chart.js/blob/master/src/plugins/plugin.filler.js). ## Filling modes
false
Other
chartjs
Chart.js
50e2ba953de8949347bbce55a7c0ff14e5dad09b.json
Use https to load scripts from CDN in samples (#4255)
samples/scales/time/combo.html
@@ -3,7 +3,7 @@ <head> <title>Line Chart - Combo Time Scale</title> - <script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script> + <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script> <script src="../../../dist/Chart.js"></script> <script src="../../utils.js"></script> <style>
true
Other
chartjs
Chart.js
50e2ba953de8949347bbce55a7c0ff14e5dad09b.json
Use https to load scripts from CDN in samples (#4255)
samples/scales/time/line-point-data.html
@@ -3,7 +3,7 @@ <head> <title>Time Scale Point Data</title> - <script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script> + <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script> <script src="../../../dist/Chart.js"></script> <script src="../../utils.js"></script> <style>
true
Other
chartjs
Chart.js
50e2ba953de8949347bbce55a7c0ff14e5dad09b.json
Use https to load scripts from CDN in samples (#4255)
samples/scales/time/line.html
@@ -3,7 +3,7 @@ <head> <title>Line Chart</title> - <script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script> + <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script> <script src="../../../dist/Chart.js"></script> <script src="../../utils.js"></script> <style>
true
Other
chartjs
Chart.js
50e2ba953de8949347bbce55a7c0ff14e5dad09b.json
Use https to load scripts from CDN in samples (#4255)
samples/tooltips/custom-points.html
@@ -5,7 +5,7 @@ <title>Custom Tooltips using Data Points</title> <script src="../../dist/Chart.bundle.js"></script> <script src="../utils.js"></script> - <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> + <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <style> canvas{ -moz-user-select: none;
true
Other
chartjs
Chart.js
c4c00b58342c5f46c5c54ec3caddd518c45fdf9f.json
Fix RequireJS doc to use UMD file instead (#4252)
docs/getting-started/integration.md
@@ -5,30 +5,32 @@ Chart.js can be integrated with plain JavaScript or with different module loader ## ES6 Modules ```javascript -import Chart from 'chart.js' -var myChart = new Chart(ctx, {...}) +import Chart from 'chart.js'; +var myChart = new Chart(ctx, {...}); ``` ## Script Tag ```html -<script src="path/to/Chartjs/dist/Chart.js"></script> +<script src="path/to/chartjs/dist/Chart.js"></script> <script> -var myChart = new Chart(ctx, {...}) + var myChart = new Chart(ctx, {...}); </script> ``` ## Common JS ```javascript -var Chart = require('chart.js') -var myChart = new Chart(ctx, {...}) +var Chart = require('chart.js'); +var myChart = new Chart(ctx, {...}); ``` ## Require JS ```javascript -require(['path/to/Chartjs/src/chartjs.js'], function(Chart){ - var myChart = new Chart(ctx, {...}) -}) -``` \ No newline at end of file +require(['path/to/chartjs/dist/Chart.js'], function(Chart){ + var myChart = new Chart(ctx, {...}); +}); +``` + +> **Important:** RequireJS [can **not** load CommonJS module as is](http://www.requirejs.org/docs/commonjs.html#intro), so be sure to require one of the built UMD files instead (i.e. `dist/Chart.js`, `dist/Chart.min.js`, etc.).
false
Other
chartjs
Chart.js
3ff5d489c14bbc1cd6b7fab383095cd2c25afe71.json
Document the new filling modes and options (#4251)
docs/SUMMARY.md
@@ -27,6 +27,7 @@ * [Polar Area](charts/polar.md) * [Bubble](charts/bubble.md) * [Scatter](charts/scatter.md) + * [Area](charts/area.md) * [Mixed](charts/mixed.md) * [Axes](axes/README.md) * [Cartesian](axes/cartesian/README.md)
true
Other
chartjs
Chart.js
3ff5d489c14bbc1cd6b7fab383095cd2c25afe71.json
Document the new filling modes and options (#4251)
docs/charts/README.md
@@ -8,4 +8,6 @@ Chart.js comes with built-in chart types: * [doughnut and pie](./doughnut.md) * [bubble](./bubble.md) -To create a new chart type, see the [developer notes](../developers/charts.md#new-charts) \ No newline at end of file +[Area charts](area.md) can be built from a line or radar chart using the dataset `fill` option. + +To create a new chart type, see the [developer notes](../developers/charts.md#new-charts)
true
Other
chartjs
Chart.js
3ff5d489c14bbc1cd6b7fab383095cd2c25afe71.json
Document the new filling modes and options (#4251)
docs/charts/area.md
@@ -0,0 +1,72 @@ +# Area Charts + +Both [line](line.md) and [radar](radar.md) charts support a `fill` option on the dataset object which can be used to create area between two datasets or a dataset and a boundary, i.e. the scale `origin`, `start` or `end` (see [filling modes](#filling-modes)). + +> **Note:** this feature is implemented by the [`filler` plugin](/chartjs/Chart.js/blob/master/src/plugins/plugin.filler.js). + +## Filling modes + +| Mode | Type | Values | +| :--- | :--- | :--- | +| Absolute dataset index <sup>1</sup> | `Number` | `1`, `2`, `3`, ... | +| Relative dataset index <sup>1</sup> | `String` | `'-1'`, `'-2'`, `'+1'`, ... | +| Boundary <sup>2</sup> | `String` | `'start'`, `'end'`, `'origin'` | +| Disabled <sup>3</sup> | `Boolean` | `false` | + +> <sup>1</sup> dataset filling modes have been introduced in version 2.6.0<br> +> <sup>2</sup> prior version 2.6.0, boundary values was `'zero'`, `'top'`, `'bottom'` (deprecated)<br> +> <sup>3</sup> for backward compatibility, `fill: true` (default) is equivalent to `fill: 'origin'`<br> + +**Example** +```javascript +new Chart(ctx, { + data: { + datasets: [ + {fill: 'origin'}, // 0: fill to 'origin' + {fill: '+2'}, // 1: fill to dataset 3 + {fill: 1}, // 2: fill to dataset 1 + {fill: false}, // 3: no fill + {fill: '-2'} // 4: fill to dataset 2 + ] + } +}) +``` + +## Configuration +| Option | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| [`plugins.filler.propagate`](#propagate) | `Boolean` | `true` | Fill propagation when target is hidden + +### propagate +Boolean (default: `true`) + +If `true`, the fill area will be recursively extended to the visible target defined by the `fill` value of hidden dataset targets: + +**Example** +```javascript +new Chart(ctx, { + data: { + datasets: [ + {fill: 'origin'}, // 0: fill to 'origin' + {fill: '-1'}, // 1: fill to dataset 0 + {fill: 1}, // 2: fill to dataset 1 + {fill: false}, // 3: no fill + {fill: '-2'} // 4: fill to dataset 2 + ] + }, + options: { + plugins: { + filler: { + propagate: true + } + } + } +}) +``` + +`propagate: true`: +- if dataset 2 is hidden, dataset 4 will fill to dataset 1 +- if dataset 2 and 1 are hidden, dataset 4 will fill to `'origin'` + +`propagate: false`: +- if dataset 2 and/or 4 are hidden, dataset 4 will not be filled
true
Other
chartjs
Chart.js
3ff5d489c14bbc1cd6b7fab383095cd2c25afe71.json
Document the new filling modes and options (#4251)
docs/charts/line.md
@@ -56,7 +56,7 @@ All point* properties can be specified as an array. If these are set to an array | `borderCapStyle` | `String` | Cap style of the line. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap) | `borderJoinStyle` | `String` | Line joint style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin) | `cubicInterpolationMode` | `String` | Algorithm used to interpolate a smooth curve from the discrete data points. [more...](#cubicInterpolationMode) -| `fill` | `Boolean/String` | How to fill the area under the line. [more...](#fill) +| `fill` | `Boolean/String` | How to fill the area under the line. See [area charts](area.md) | `lineTension` | `Number` | Bezier curve tension of the line. Set to 0 to draw straightlines. This option is ignored if monotone cubic interpolation is used. | `pointBackgroundColor` | `Color/Color[]` | The fill color for points. | `pointBorderColor` | `Color/Color[]` | The border color for points. @@ -77,20 +77,12 @@ The following interpolation modes are supported: * 'default' * 'monotone'. -The 'default' algorithm uses a custom weighted cubic interpolation, which produces pleasant curves for all types of datasets. +The 'default' algorithm uses a custom weighted cubic interpolation, which produces pleasant curves for all types of datasets. -The 'monotone' algorithm is more suited to `y = f(x)` datasets : it preserves monotonicity (or piecewise monotonicity) of the dataset being interpolated, and ensures local extremums (if any) stay at input data points. +The 'monotone' algorithm is more suited to `y = f(x)` datasets : it preserves monotonicity (or piecewise monotonicity) of the dataset being interpolated, and ensures local extremums (if any) stay at input data points. If left untouched (`undefined`), the global `options.elements.line.cubicInterpolationMode` property is used. -### fill -If `true`, fill the area under the line. The line is filled to the baseline. If the y axis has a 0 value, the line is filled to that point. If the axis has only negative values, the line is filled to the highest value. If the axis has only positive values, it is filled to the lowest value. - -String values to fill to specific locations are: -* `'zero'` -* `'top'` -* `'bottom'` - ### pointStyle The style of point. Options are: * 'circle' @@ -246,4 +238,4 @@ new Chart(ctx, { responsiveAnimationDuration: 0, // animation duration after a resize } }); -``` \ No newline at end of file +```
true
Other
chartjs
Chart.js
3ff5d489c14bbc1cd6b7fab383095cd2c25afe71.json
Document the new filling modes and options (#4251)
docs/charts/radar.md
@@ -76,8 +76,8 @@ All point* properties can be specified as an array. If these are set to an array | `borderDashOffset` | `Number` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset) | `borderCapStyle` | `String` | Cap style of the line. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap) | `borderJoinStyle` | `String` | Line joint style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin) -| `fill` | `Boolean/String` | How to fill the area under the line. [more...](#fill) -| `lineTension` | `Number` | Bezier curve tension of the line. Set to 0 to draw straightlines. +| `fill` | `Boolean/String` | How to fill the area under the line. See [area charts](area.md) +| `lineTension` | `Number` | Bezier curve tension of the line. Set to 0 to draw straightlines. | `pointBackgroundColor` | `Color/Color[]` | The fill color for points. | `pointBorderColor` | `Color/Color[]` | The border color for points. | `pointBorderWidth` | `Number/Number[]` | The width of the point border in pixels. @@ -142,4 +142,4 @@ data: { data: [20, 10, 4, 2] }] } -``` \ No newline at end of file +```
true
Other
chartjs
Chart.js
3ff5d489c14bbc1cd6b7fab383095cd2c25afe71.json
Document the new filling modes and options (#4251)
docs/style.css
@@ -9,3 +9,7 @@ a.anchorjs-link { a.anchorjs-link:hover { color: rgba(65, 131, 196, 1); } + +sup { + font-size: 0.75em !important; +}
true
Other
chartjs
Chart.js
9f793a715fd9033ae475d5d524733668b7492c91.json
Remove unnecessary variable
src/scales/scale.time.js
@@ -318,7 +318,7 @@ module.exports = function(Chart) { me.displayFormat = timeOpts.displayFormats[unit]; var stepSize = timeOpts.stepSize || determineStepSize(minTimestamp || dataMin, maxTimestamp || dataMax, unit, maxTicks); - var ticks = me.ticks = Chart.Ticks.generators.time({ + me.ticks = Chart.Ticks.generators.time({ maxTicks: maxTicks, min: minTimestamp, max: maxTimestamp, @@ -332,8 +332,8 @@ module.exports = function(Chart) { // At this point, we need to update our max and min given the tick values since we have expanded the // range of the scale - me.max = helpers.max(ticks); - me.min = helpers.min(ticks); + me.max = helpers.max(me.ticks); + me.min = helpers.min(me.ticks); }, // Get tooltip label getLabelForIndex: function(index, datasetIndex) {
false
Other
chartjs
Chart.js
f0c6b3f8342e2406c250329336037a7f7004284e.json
Fix legend and title layout options update
src/core/core.layoutService.js
@@ -54,18 +54,19 @@ module.exports = function(Chart) { * Register a box to a chart. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title. * @param {Chart} chart - the chart to use - * @param {ILayoutItem} layoutItem - the item to add to be layed out + * @param {ILayoutItem} item - the item to add to be layed out */ - addBox: function(chart, layoutItem) { + addBox: function(chart, item) { if (!chart.boxes) { chart.boxes = []; } - // Ensure that all layout items have a weight - if (!layoutItem.weight) { - layoutItem.weight = 0; - } - chart.boxes.push(layoutItem); + // initialize item with default values + item.fullWidth = item.fullWidth || false; + item.position = item.position || 'top'; + item.weight = item.weight || 0; + + chart.boxes.push(item); }, /** @@ -80,6 +81,26 @@ module.exports = function(Chart) { } }, + /** + * Sets (or updates) options on the given `item`. + * @param {Chart} chart - the chart in which the item lives (or will be added to) + * @param {Object} item - the item to configure with the given options + * @param {Object} options - the new item options. + */ + configure: function(chart, item, options) { + var props = ['fullWidth', 'position', 'weight']; + var ilen = props.length; + var i = 0; + var prop; + + for (; i<ilen; ++i) { + prop = props[i]; + if (options.hasOwnProperty(prop)) { + item[prop] = options[prop]; + } + } + }, + /** * Fits boxes of the given chart into the given size by having each box measure itself * then running a fitting algorithm
true
Other
chartjs
Chart.js
f0c6b3f8342e2406c250329336037a7f7004284e.json
Fix legend and title layout options update
src/plugins/plugin.legend.js
@@ -3,14 +3,15 @@ module.exports = function(Chart) { var helpers = Chart.helpers; + var layout = Chart.layoutService; var noop = helpers.noop; Chart.defaults.global.legend = { - display: true, position: 'top', - fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes) + fullWidth: true, reverse: false, + weight: 1000, // a callback that will handle onClick: function(e, legendItem) { @@ -495,16 +496,12 @@ module.exports = function(Chart) { var legend = new Chart.Legend({ ctx: chart.ctx, options: legendOpts, - chart: chart, - - // ILayoutItem parameters for layout service - // pick a large number to ensure we are on the outside after any axes - weight: 1000, - position: legendOpts.position, - fullWidth: legendOpts.fullWidth, + chart: chart }); + + layout.configure(chart, legend, legendOpts); + layout.addBox(chart, legend); chart.legend = legend; - Chart.layoutService.addBox(chart, legend); } return { @@ -517,6 +514,7 @@ module.exports = function(Chart) { createNewLegendAndAttach(chart, legendOpts); } }, + beforeUpdate: function(chart) { var legendOpts = chart.options.legend; var legend = chart.legend; @@ -525,15 +523,17 @@ module.exports = function(Chart) { legendOpts = helpers.configMerge(Chart.defaults.global.legend, legendOpts); if (legend) { + layout.configure(chart, legend, legendOpts); legend.options = legendOpts; } else { createNewLegendAndAttach(chart, legendOpts); } } else if (legend) { - Chart.layoutService.removeBox(chart, legend); + layout.removeBox(chart, legend); delete chart.legend; } }, + afterEvent: function(chart, e) { var legend = chart.legend; if (legend) {
true
Other
chartjs
Chart.js
f0c6b3f8342e2406c250329336037a7f7004284e.json
Fix legend and title layout options update
src/plugins/plugin.title.js
@@ -3,13 +3,14 @@ module.exports = function(Chart) { var helpers = Chart.helpers; + var layout = Chart.layoutService; var noop = helpers.noop; Chart.defaults.global.title = { display: false, position: 'top', - fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes) - + fullWidth: true, + weight: 2000, // by default greater than legend (1000) to be above fontStyle: 'bold', padding: 10, @@ -184,15 +185,12 @@ module.exports = function(Chart) { var title = new Chart.Title({ ctx: chart.ctx, options: titleOpts, - chart: chart, - - // ILayoutItem parameters - weight: 2000, // greater than legend to be above - position: titleOpts.position, - fullWidth: titleOpts.fullWidth, + chart: chart }); + + layout.configure(chart, title, titleOpts); + layout.addBox(chart, title); chart.titleBlock = title; - Chart.layoutService.addBox(chart, title); } return { @@ -205,6 +203,7 @@ module.exports = function(Chart) { createNewTitleBlockAndAttach(chart, titleOpts); } }, + beforeUpdate: function(chart) { var titleOpts = chart.options.title; var titleBlock = chart.titleBlock; @@ -213,6 +212,7 @@ module.exports = function(Chart) { titleOpts = helpers.configMerge(Chart.defaults.global.title, titleOpts); if (titleBlock) { + layout.configure(chart, titleBlock, titleOpts); titleBlock.options = titleOpts; } else { createNewTitleBlockAndAttach(chart, titleOpts);
true
Other
chartjs
Chart.js
f0c6b3f8342e2406c250329336037a7f7004284e.json
Fix legend and title layout options update
test/specs/plugin.legend.tests.js
@@ -11,6 +11,7 @@ describe('Legend block tests', function() { position: 'top', fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes) reverse: false, + weight: 1000, // a callback that will handle onClick: jasmine.any(Function), @@ -391,6 +392,33 @@ describe('Legend block tests', function() { expect(chart.legend.options.display).toBe(false); }); + it ('should update the associated layout item', function() { + var chart = acquireChart({ + type: 'line', + data: {}, + options: { + legend: { + fullWidth: true, + position: 'top', + weight: 150 + } + } + }); + + expect(chart.legend.fullWidth).toBe(true); + expect(chart.legend.position).toBe('top'); + expect(chart.legend.weight).toBe(150); + + chart.options.legend.fullWidth = false; + chart.options.legend.position = 'left'; + chart.options.legend.weight = 42; + chart.update(); + + expect(chart.legend.fullWidth).toBe(false); + expect(chart.legend.position).toBe('left'); + expect(chart.legend.weight).toBe(42); + }); + it ('should remove the legend if the new options are false', function() { var chart = acquireChart({ type: 'line',
true
Other
chartjs
Chart.js
f0c6b3f8342e2406c250329336037a7f7004284e.json
Fix legend and title layout options update
test/specs/plugin.title.tests.js
@@ -11,6 +11,7 @@ describe('Title block tests', function() { display: false, position: 'top', fullWidth: true, + weight: 2000, fontStyle: 'bold', padding: 10, text: '' @@ -231,6 +232,33 @@ describe('Title block tests', function() { expect(chart.titleBlock.options.display).toBe(false); }); + it ('should update the associated layout item', function() { + var chart = acquireChart({ + type: 'line', + data: {}, + options: { + title: { + fullWidth: true, + position: 'top', + weight: 150 + } + } + }); + + expect(chart.titleBlock.fullWidth).toBe(true); + expect(chart.titleBlock.position).toBe('top'); + expect(chart.titleBlock.weight).toBe(150); + + chart.options.title.fullWidth = false; + chart.options.title.position = 'left'; + chart.options.title.weight = 42; + chart.update(); + + expect(chart.titleBlock.fullWidth).toBe(false); + expect(chart.titleBlock.position).toBe('left'); + expect(chart.titleBlock.weight).toBe(42); + }); + it ('should remove the title if the new options are false', function() { var chart = acquireChart({ type: 'line',
true
Other
chartjs
Chart.js
8811759e1c986fff719af3a0cd2cbdfdcef8ae79.json
Remove malformed comment Fixes https://github.com/chartjs/Chart.js/issues/4181
src/scales/scale.category.js
@@ -18,7 +18,7 @@ module.exports = function(Chart) { var data = this.chart.data; return (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels; }, - // Implement this so that + determineDataLimits: function() { var me = this; var labels = me.getLabels();
false
Other
chartjs
Chart.js
f2c569ef25320f26c442cfde4238a2fb536d4888.json
Enhance the responsive documentation Make sure to explain responsiveness limitations with CANVAS elements and how to correctly setup a responsive chart using a dedicated and relatively positioned div wrapper.
docs/general/responsive.md
@@ -1,10 +1,35 @@ # Responsive Charts -Chart.js provides a few options for controlling resizing behaviour of charts. +When it comes to change the chart size based on the window size, a major limitation is that the canvas *render* size (`canvas.width` and `.height`) can **not** be expressed with relative values, contrary to the *display* size (`canvas.style.width` and `.height`). Furthermore, these sizes are independent from each other and thus the canvas *render* size does not adjust automatically based on the *display* size, making the rendering inaccurate. + +The following examples **do not work**: + +- `<canvas height="40vh" width="80vw">`: **invalid** values, the canvas doesn't resize ([example](https://codepen.io/chartjs/pen/oWLZaR)) +- `<canvas style="height:40vh; width:80vw">`: **invalid** behavior, the canvas is resized but becomes blurry ([example](https://codepen.io/chartjs/pen/WjxpmO)) + +Chart.js provides a [few options](#configuration-options) to enable responsiveness and control the resize behavior of charts by detecting when the canvas *display* size changes and update the *render* size accordingly. + +## Configuration Options | Name | Type | Default | Description | ---- | ---- | ------- | ----------- -| `responsive` | `Boolean` | `true` | Resizes the chart canvas when its container does. +| `responsive` | `Boolean` | `true` | Resizes the chart canvas when its container does ([important note...](#important-note)). | `responsiveAnimationDuration` | `Number` | `0` | Duration in milliseconds it takes to animate to new size after a resize event. | `maintainAspectRatio` | `Boolean` | `true` | Maintain the original canvas aspect ratio `(width / height)` when resizing. -| `onResize` | `Function` | `null` | Called when a resize occurs. Gets passed two arguments: the chart instance and the new size. \ No newline at end of file +| `onResize` | `Function` | `null` | Called when a resize occurs. Gets passed two arguments: the chart instance and the new size. + +## Important Note + +Detecting when the canvas size changes can not be done directly from the `CANVAS` element. Chart.js uses its parent container to update the canvas *render* and *display* sizes. However, this method requires the container to be **relatively positioned**. It's also strongly recommended to **dedicate this container to the chart canvas only**. Responsiveness can then be achieved by setting relative values for the container size ([example](https://codepen.io/chartjs/pen/YVWZbz)): + +```html +<div class="chart-container" style="position: relative; height:40vh; width:80vw"> + <canvas id="chart"></canvas> +</div> +``` + +The chart can also be programmatically resized by modifying the container size: + +```javascript +chart.canvas.parentNode.style.height = '128px'; +```
false
Other
chartjs
Chart.js
3ec6377f11a97310ea23ca7725a08c5c70eb35df.json
Fix hidden charts hanging the browser Ensure width cannot be greater than maxWidth. Similar to `minSize.height` calculation.
src/core/core.scale.js
@@ -356,7 +356,7 @@ module.exports = function(Chart) { } else { largestTextWidth += me.options.ticks.padding; } - minSize.width += largestTextWidth; + minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth); me.paddingTop = tickFont.size / 2; me.paddingBottom = tickFont.size / 2; }
true
Other
chartjs
Chart.js
3ec6377f11a97310ea23ca7725a08c5c70eb35df.json
Fix hidden charts hanging the browser Ensure width cannot be greater than maxWidth. Similar to `minSize.height` calculation.
src/scales/scale.time.js
@@ -145,18 +145,19 @@ module.exports = function(Chart) { var unitSizeInMilliSeconds = unitDefinition.size; var sizeInUnits = Math.ceil((max - min) / unitSizeInMilliSeconds); var multiplier = 1; + var range = max - min; if (unitDefinition.steps) { // Have an array of steps var numSteps = unitDefinition.steps.length; for (var i = 0; i < numSteps && sizeInUnits > maxTicks; i++) { multiplier = unitDefinition.steps[i]; - sizeInUnits = Math.ceil((max - min) / (unitSizeInMilliSeconds * multiplier)); + sizeInUnits = Math.ceil(range / (unitSizeInMilliSeconds * multiplier)); } } else { - while (sizeInUnits > maxTicks) { + while (sizeInUnits > maxTicks && maxTicks > 0) { ++multiplier; - sizeInUnits = Math.ceil((max - min) / (unitSizeInMilliSeconds * multiplier)); + sizeInUnits = Math.ceil(range / (unitSizeInMilliSeconds * multiplier)); } }
true
Other
chartjs
Chart.js
3ec6377f11a97310ea23ca7725a08c5c70eb35df.json
Fix hidden charts hanging the browser Ensure width cannot be greater than maxWidth. Similar to `minSize.height` calculation.
test/specs/scale.time.tests.js
@@ -471,4 +471,34 @@ describe('Time scale tests', function() { unit: 'day', }); }); + + it('does not create a negative width chart when hidden', function() { + var chart = window.acquireChart({ + type: 'line', + data: { + datasets: [{ + data: [] + }] + }, + options: { + scales: { + xAxes: [{ + type: 'time', + time: { + min: moment().subtract(1, 'months'), + max: moment(), + } + }], + }, + responsive: true, + }, + }, { + wrapper: { + style: 'display: none', + }, + }); + expect(chart.scales['y-axis-0'].width).toEqual(0); + expect(chart.scales['y-axis-0'].maxWidth).toEqual(0); + expect(chart.width).toEqual(0); + }); });
true
Other
chartjs
Chart.js
86fb98eb3720a7256764ff0bd8b34a23c0946ade.json
Remove extraneous period
README.md
@@ -33,7 +33,7 @@ You can find documentation at [www.chartjs.org/docs](http://www.chartjs.org/docs ## Contributing -Before submitting an issue or a pull request, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md.) first. For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chartjs). +Before submitting an issue or a pull request, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first. For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chartjs). ## Building Instructions on building and testing Chart.js can be found in [the documentation](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md#building-and-testing).
false
Other
chartjs
Chart.js
ecac839f68791788d1d5a88fe8eb4d007c8f6fbd.json
Fix broken link to point to correct sample file.
samples/samples.js
@@ -111,7 +111,7 @@ path: 'scales/time/line.html' }, { title: 'Line (point data)', - path: 'scales/time/line.html' + path: 'scales/time/line-point-data.html' }, { title: 'Combo', path: 'scales/time/combo.html'
false
Other
chartjs
Chart.js
9ea18065add95d80a807e67f27018caadcfeb44c.json
Add live samples back to docs for each chart type
docs/charts/bar.md
@@ -1,6 +1,56 @@ # Bar A bar chart provides a way of showing data values represented as vertical bars. It is sometimes used to show trend data, and the comparison of multiple data sets side by side. +{% chartjs %} +{ + "type": "bar", + "data": { + "labels": [ + "January", + "February", + "March", + "April", + "May", + "June", + "July" + ], + "datasets": [{ + "label": "My First Dataset", + "data": [65, 59, 80, 81, 56, 55, 40], + "fill": false, + "backgroundColor": [ + "rgba(255, 99, 132, 0.2)", + "rgba(255, 159, 64, 0.2)", + "rgba(255, 205, 86, 0.2)", + "rgba(75, 192, 192, 0.2)", + "rgba(54, 162, 235, 0.2)", + "rgba(153, 102, 255, 0.2)", + "rgba(201, 203, 207, 0.2)" + ], + "borderColor": [ + "rgb(255, 99, 132)", + "rgb(255, 159, 64)", + "rgb(255, 205, 86)", + "rgb(75, 192, 192)", + "rgb(54, 162, 235)", + "rgb(153, 102, 255)", + "rgb(201, 203, 207)" + ], + "borderWidth": 1 + }] + }, + "options": { + "scales": { + "yAxes": [{ + "ticks": { + "beginAtZero": true + } + }] + } + } +} +{% endchartjs %} + ## Example Usage ```javascript var myBarChart = new Chart(ctx, { @@ -133,6 +183,47 @@ The following dataset properties are specific to stacked bar charts. # Horizontal Bar Chart A horizontal bar chart is a variation on a vertical bar chart. It is sometimes used to show trend data, and the comparison of multiple data sets side by side. +{% chartjs %} +{ + "type": "horizontalBar", + "data": { + "labels": ["January", "February", "March", "April", "May", "June", "July"], + "datasets": [{ + "label": "My First Dataset", + "data": [65, 59, 80, 81, 56, 55, 40], + "fill": false, + "backgroundColor": [ + "rgba(255, 99, 132, 0.2)", + "rgba(255, 159, 64, 0.2)", + "rgba(255, 205, 86, 0.2)", + "rgba(75, 192, 192, 0.2)", + "rgba(54, 162, 235, 0.2)", + "rgba(153, 102, 255, 0.2)", + "rgba(201, 203, 207, 0.2)" + ], + "borderColor": [ + "rgb(255, 99, 132)", + "rgb(255, 159, 64)", + "rgb(255, 205, 86)", + "rgb(75, 192, 192)", + "rgb(54, 162, 235)", + "rgb(153, 102, 255)", + "rgb(201, 203, 207)" + ], + "borderWidth": 1 + }] + }, + "options": { + "scales": { + "xAxes": [{ + "ticks": { + "beginAtZero": true + } + }] + } + } +} +{% endchartjs %} ## Example ```javascript
true
Other
chartjs
Chart.js
9ea18065add95d80a807e67f27018caadcfeb44c.json
Add live samples back to docs for each chart type
docs/charts/bubble.md
@@ -2,6 +2,27 @@ A bubble chart is used to display three dimensions of data at the same time. The location of the bubble is determined by the first two dimensions and the corresponding horizontal and vertical axes. The third dimension is represented by the size of the individual bubbles. +{% chartjs %} +{ + "type": "bubble", + "data": { + "datasets": [{ + "label": "First Dataset", + "data": [{ + "x": 20, + "y": 30, + "r": 15 + }, { + "x": 40, + "y": 10, + "r": 10 + }], + "backgroundColor": "rgb(255, 99, 132)" + }] + }, +} +{% endchartjs %} + ## Example Usage ```javascript
true
Other
chartjs
Chart.js
9ea18065add95d80a807e67f27018caadcfeb44c.json
Add live samples back to docs for each chart type
docs/charts/doughnut.md
@@ -7,6 +7,28 @@ Pie and doughnut charts are effectively the same class in Chart.js, but have one They are also registered under two aliases in the `Chart` core. Other than their different default value, and different alias, they are exactly the same. +{% chartjs %} +{ + "type": "doughnut", + "data": { + "labels": [ + "Red", + "Blue", + "Yellow", + ], + "datasets": [{ + "label": "My First Dataset", + "data": [300, 50, 100], + "backgroundColor": [ + "rgb(255, 99, 132)", + "rgb(54, 162, 235)", + "rgb(255, 205, 86)", + ] + }] + }, +} +{% endchartjs %} + ## Example Usage ```javascript
true
Other
chartjs
Chart.js
9ea18065add95d80a807e67f27018caadcfeb44c.json
Add live samples back to docs for each chart type
docs/charts/line.md
@@ -1,6 +1,33 @@ # Line A line chart is a way of plotting data points on a line. Often, it is used to show trend data, or the comparison of two data sets. +{% chartjs %} +{ + "type": "line", + "data": { + "labels": [ + "January", + "February", + "March", + "April", + "May", + "June", + "July" + ], + "datasets": [{ + "label": "My First Dataset", + "data": [65, 59, 80, 81, 56, 55, 40], + "fill": false, + "borderColor": "rgb(75, 192, 192)", + "lineTension": 0.1 + }] + }, + "options": { + + } +} +{% endchartjs %} + ## Example Usage ```javascript var myLineChart = new Chart(ctx, {
true
Other
chartjs
Chart.js
9ea18065add95d80a807e67f27018caadcfeb44c.json
Add live samples back to docs for each chart type
docs/charts/mixed.md
@@ -34,4 +34,39 @@ var mixedChart = new Chart(ctx, { }); ``` -At this point we have a chart rendering how we'd like. It's important to note that the default options for a line chart are not merged in this case. Only the options for the default type are merged in. In this case, that means that the default options for a bar chart are merged because that is the type specified by the `type` field. \ No newline at end of file +At this point we have a chart rendering how we'd like. It's important to note that the default options for a line chart are not merged in this case. Only the options for the default type are merged in. In this case, that means that the default options for a bar chart are merged because that is the type specified by the `type` field. + +{% chartjs %} +{ + "type": "bar", + "data": { + "labels": [ + "January", + "February", + "March", + "April" + ], + "datasets": [{ + "label": "Bar Dataset", + "data": [10, 20, 30, 40], + "borderColor": "rgb(255, 99, 132)", + "backgroundColor": "rgba(255, 99, 132, 0.2)" + }, { + "label": "Line Dataset", + "data": [50, 50, 50, 50], + "type": "line", + "fill": false, + "borderColor": "rgb(54, 162, 235)" + }] + }, + "options": { + "scales": { + "yAxes": [{ + "ticks": { + "beginAtZero": true + } + }] + } + } +} +{% endchartjs %}
true
Other
chartjs
Chart.js
9ea18065add95d80a807e67f27018caadcfeb44c.json
Add live samples back to docs for each chart type
docs/charts/polar.md
@@ -4,6 +4,32 @@ Polar area charts are similar to pie charts, but each segment has the same angle This type of chart is often useful when we want to show a comparison data similar to a pie chart, but also show a scale of values for context. +{% chartjs %} +{ + "type": "polarArea", + "data": { + "labels": [ + "Red", + "Green", + "Yellow", + "Grey", + "Blue" + ], + "datasets": [{ + "label": "My First Dataset", + "data": [11, 16, 7, 3, 14], + "backgroundColor": [ + "rgb(255, 99, 132)", + "rgb(75, 192, 192)", + "rgb(255, 205, 86)", + "rgb(201, 203, 207)", + "rgb(54, 162, 235)" + ] + }] + }, +} +{% endchartjs %} + ## Example Usage ```javascript
true
Other
chartjs
Chart.js
9ea18065add95d80a807e67f27018caadcfeb44c.json
Add live samples back to docs for each chart type
docs/charts/radar.md
@@ -3,6 +3,54 @@ A radar chart is a way of showing multiple data points and the variation between They are often useful for comparing the points of two or more different data sets. +{% chartjs %} +{ + "type": "radar", + "data": { + "labels": [ + "Eating", + "Drinking", + "Sleeping", + "Designing", + "Coding", + "Cycling", + "Running" + ], + "datasets": [{ + "label": "My First Dataset", + "data": [65, 59, 90, 81, 56, 55, 40], + "fill": true, + "backgroundColor": "rgba(255, 99, 132, 0.2)", + "borderColor": "rgb(255, 99, 132)", + "pointBackgroundColor": "rgb(255, 99, 132)", + "pointBorderColor": "#fff", + "pointHoverBackgroundColor": "#fff", + "pointHoverBorderColor": "rgb(255, 99, 132)", + "fill": true + }, { + "label": "My Second Dataset", + "data": [28, 48, 40, 19, 96, 27, 100], + "fill": true, + "backgroundColor": "rgba(54, 162, 235, 0.2)", + "borderColor": "rgb(54, 162, 235)", + "pointBackgroundColor": "rgb(54, 162, 235)", + "pointBorderColor": "#fff", + "pointHoverBackgroundColor": "#fff", + "pointHoverBorderColor": "rgb(54, 162, 235)", + "fill": true + }] + }, + "options": { + "elements": { + "line": { + "tension": 0, + "borderWidth": 3 + } + } + } +} +{% endchartjs %} + ## Example Usage ```javascript var myRadarChart = new Chart(ctx, {
true
Other
chartjs
Chart.js
c96ad6694559f7f280c4727d1f5e52a296d933a2.json
Update line-customTooltips.html (Re issue #4038 ) Add window scroll position to tooltip position calculation so they show up in the intended place instead of potentially off-screen! Moved tooltips inside the canvas parent container since they are being positioned in terms of its location
samples/tooltips/custom-line.html
@@ -48,7 +48,7 @@ tooltipEl = document.createElement('div'); tooltipEl.id = 'chartjs-tooltip'; tooltipEl.innerHTML = "<table></table>" - document.body.appendChild(tooltipEl); + this._chart.canvas.parentNode.appendChild(tooltipEl); } // Hide if no tooltip @@ -95,12 +95,13 @@ tableRoot.innerHTML = innerHtml; } - var position = this._chart.canvas.getBoundingClientRect(); + var positionY = this._chart.canvas.offsetTop; + var positionX = this._chart.canvas.offsetLeft; // Display, position, and set styles for font tooltipEl.style.opacity = 1; - tooltipEl.style.left = position.left + tooltip.caretX + 'px'; - tooltipEl.style.top = position.top + tooltip.caretY + 'px'; + tooltipEl.style.left = positionX + tooltip.caretX + 'px'; + tooltipEl.style.top = positionY + tooltip.caretY + 'px'; tooltipEl.style.fontFamily = tooltip._fontFamily; tooltipEl.style.fontSize = tooltip.fontSize; tooltipEl.style.fontStyle = tooltip._fontStyle;
true
Other
chartjs
Chart.js
c96ad6694559f7f280c4727d1f5e52a296d933a2.json
Update line-customTooltips.html (Re issue #4038 ) Add window scroll position to tooltip position calculation so they show up in the intended place instead of potentially off-screen! Moved tooltips inside the canvas parent container since they are being positioned in terms of its location
samples/tooltips/custom-pie.html
@@ -36,11 +36,10 @@ <body> <div id="canvas-holder" style="width: 300px;"> - <canvas id="chart-area" width="300" height="300" /> - </div> - - <div id="chartjs-tooltip"> - <table></table> + <canvas id="chart-area" width="300" height="300"></canvas> + <div id="chartjs-tooltip"> + <table></table> + </div> </div> <script> @@ -92,12 +91,13 @@ tableRoot.innerHTML = innerHtml; } - var position = this._chart.canvas.getBoundingClientRect(); + var positionY = this._chart.canvas.offsetTop; + var positionX = this._chart.canvas.offsetLeft; // Display, position, and set styles for font tooltipEl.style.opacity = 1; - tooltipEl.style.left = position.left + tooltip.caretX + 'px'; - tooltipEl.style.top = position.top + tooltip.caretY + 'px'; + tooltipEl.style.left = positionX + tooltip.caretX + 'px'; + tooltipEl.style.top = positionY + tooltip.caretY + 'px'; tooltipEl.style.fontFamily = tooltip._fontFamily; tooltipEl.style.fontSize = tooltip.fontSize; tooltipEl.style.fontStyle = tooltip._fontStyle;
true
Other
chartjs
Chart.js
c96ad6694559f7f280c4727d1f5e52a296d933a2.json
Update line-customTooltips.html (Re issue #4038 ) Add window scroll position to tooltip position calculation so they show up in the intended place instead of potentially off-screen! Moved tooltips inside the canvas parent container since they are being positioned in terms of its location
samples/tooltips/custom-points.html
@@ -37,13 +37,16 @@ <body> <div id="canvas-holder1" style="width:75%;"> <canvas id="chart1"></canvas> + <div class="chartjs-tooltip" id="tooltip-0"></div> + <div class="chartjs-tooltip" id="tooltip-1"></div> </div> - <div class="chartjs-tooltip" id="tooltip-0"></div> - <div class="chartjs-tooltip" id="tooltip-1"></div> <script> var customTooltips = function (tooltip) { $(this._chart.canvas).css("cursor", "pointer"); + var positionY = this._chart.canvas.offsetTop; + var positionX = this._chart.canvas.offsetLeft; + $(".chartjs-tooltip").css({ opacity: 0, }); @@ -60,8 +63,8 @@ $tooltip.html(content); $tooltip.css({ opacity: 1, - top: dataPoint.y + "px", - left: dataPoint.x + "px", + top: positionY + dataPoint.y + "px", + left: positionX + dataPoint.x + "px", }); }); }
true
Other
chartjs
Chart.js
da1d1ca5125b7fc6e90dd49b0656f3d82311e8e7.json
Avoid errors when rendering serverside (#3909)
src/chart.js
@@ -56,4 +56,7 @@ plugins.push(require('./plugins/plugin.filler.js')(Chart)); Chart.plugins.register(plugins); -window.Chart = module.exports = Chart; +module.exports = Chart; +if (typeof window !== 'undefined') { + window.Chart = Chart; +}
true
Other
chartjs
Chart.js
da1d1ca5125b7fc6e90dd49b0656f3d82311e8e7.json
Avoid errors when rendering serverside (#3909)
src/core/core.helpers.js
@@ -669,6 +669,11 @@ module.exports = function(Chart) { }; // Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ helpers.requestAnimFrame = (function() { + if (typeof window === 'undefined') { + return function(callback) { + callback(); + }; + } return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame ||
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
.gitignore
@@ -1,13 +1,12 @@ +/_book /coverage /custom /dist /docs/index.md /node_modules - .DS_Store .idea .vscode bower.json - *.log *.swp
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
book.json
@@ -0,0 +1,19 @@ +{ + "root": "./docs", + "author": "chartjs", + "gitbook": "3.2.2", + "plugins": ["anchorjs", "chartjs"], + "pluginsConfig": { + "anchorjs": { + "icon": "#", + "placement": "left", + "visible": "always" + }, + "theme-default": { + "showLevel": false, + "styles": { + "website": "style.css" + } + } + } +}
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
docs/00-Getting-Started.md
@@ -1,126 +0,0 @@ ---- -title: Getting started -anchor: getting-started ---- - -### Download Chart.js - -You can download the latest version of [Chart.js on GitHub](https://github.com/chartjs/Chart.js/releases/latest) or just use these [Chart.js CDN](https://cdnjs.com/libraries/Chart.js) links. -If you download or clone the repository, you must run `gulp build` to generate the dist files. Chart.js no longer comes with prebuilt release versions, so an alternative option to downloading the repo is **strongly** advised. - -### Installation - -#### npm - -```bash -npm install chart.js --save -``` - -#### bower - -```bash -bower install chart.js --save -``` - -### Selecting the Correct Build - -Chart.js provides two different builds that are available for your use. The `Chart.js` and `Chart.min.js` files include Chart.js and the accompanying color parsing library. If this version is used and you require the use of the time axis, [Moment.js](http://momentjs.com/) will need to be included before Chart.js. - -The `Chart.bundle.js` and `Chart.bundle.min.js` builds include Moment.js in a single file. This version should be used if you require time axes and want a single file to include, select this version. Do not use this build if your application already includes Moment.js. If you do, Moment.js will be included twice, increasing the page load time and potentially introducing version issues. - -### Usage - -To import Chart.js using an old-school script tag: - -```html -<script src="Chart.js"></script> -<script> - var myChart = new Chart({...}) -</script> -``` - -To import Chart.js using an awesome module loader: - -```javascript - -// Using CommonJS -var Chart = require('chart.js') -var myChart = new Chart({...}) - -// ES6 -import Chart from 'chart.js' -let myChart = new Chart({...}) - -// Using requirejs -require(['path/to/Chartjs'], function(Chart){ - var myChart = new Chart({...}) -}) - -``` - -### Creating a Chart - -To create a chart, we need to instantiate the `Chart` class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart. Here's an example. - -```html -<canvas id="myChart" width="400" height="400"></canvas> -``` - -```javascript -// Any of the following formats may be used -var ctx = document.getElementById("myChart"); -var ctx = document.getElementById("myChart").getContext("2d"); -var ctx = $("#myChart"); -var ctx = "myChart"; -``` - -Once you have the element or context, you're ready to instantiate a pre-defined chart-type or create your own! - -The following example instantiates a bar chart showing the number of votes for different colors and the y-axis starting at 0. - -```html -<canvas id="myChart" width="400" height="400"></canvas> -<script> -var ctx = document.getElementById("myChart"); -var myChart = new Chart(ctx, { - type: 'bar', - data: { - labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], - datasets: [{ - label: '# of Votes', - data: [12, 19, 3, 5, 2, 3], - backgroundColor: [ - 'rgba(255, 99, 132, 0.2)', - 'rgba(54, 162, 235, 0.2)', - 'rgba(255, 206, 86, 0.2)', - 'rgba(75, 192, 192, 0.2)', - 'rgba(153, 102, 255, 0.2)', - 'rgba(255, 159, 64, 0.2)' - ], - borderColor: [ - 'rgba(255,99,132,1)', - 'rgba(54, 162, 235, 1)', - 'rgba(255, 206, 86, 1)', - 'rgba(75, 192, 192, 1)', - 'rgba(153, 102, 255, 1)', - 'rgba(255, 159, 64, 1)' - ], - borderWidth: 1 - }] - }, - options: { - scales: { - yAxes: [{ - ticks: { - beginAtZero:true - } - }] - } - } -}); -</script> -``` - -It's that easy to get started using Chart.js! From here you can explore the many options that can help you customise your charts with scales, tooltips, labels, colors, custom actions, and much more. - -There are many examples of Chart.js that are available in the `/samples` folder of `Chart.js.zip` that is attatched to every [release](https://github.com/chartjs/Chart.js/releases).
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
docs/01-Chart-Configuration.md
@@ -1,511 +0,0 @@ ---- -title: Chart Configuration -anchor: chart-configuration ---- - -Chart.js provides a number of options for changing the behaviour of created charts. These configuration options can be changed on a per chart basis by passing in an options object when creating the chart. Alternatively, the global configuration can be changed which will be used by all charts created after that point. - -### Chart Data - -To display data, the chart must be passed a data object that contains all of the information needed by the chart. The data object can contain the following parameters - -Name | Type | Description ---- | --- | ---- -datasets | Array[object] | Contains data for each dataset. See the documentation for each chart type to determine the valid options that can be attached to the dataset -labels | Array[string] | Optional parameter that is used with the [category axis](#scales-category-scale). -xLabels | Array[string] | Optional parameter that is used with the category axis and is used if the axis is horizontal -yLabels | Array[string] | Optional parameter that is used with the category axis and is used if the axis is vertical - -### Creating a Chart with Options - -To create a chart with configuration options, simply pass an object containing your configuration to the constructor. In the example below, a line chart is created and configured to not be responsive. - -```javascript -var chart = new Chart(ctx, { - type: 'line', - data: data, - options: { - responsive: false - } -}); -``` - -### Global Configuration - -This concept was introduced in Chart.js 1.0 to keep configuration [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), and allow for changing options globally across chart types, avoiding the need to specify options for each instance, or the default for a particular chart type. - -Chart.js merges the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. This way you can be as specific as you would like in your individual chart configuration, while still changing the defaults for all chart types where applicable. The global general options are defined in `Chart.defaults.global`. The defaults for each chart type are discussed in the documentation for that chart type. - -The following example would set the hover mode to 'nearest' for all charts where this was not overridden by the chart type defaults or the options passed to the constructor on creation. - -```javascript -Chart.defaults.global.hover.mode = 'nearest'; - -// Hover mode is set to nearest because it was not overridden here -var chartHoverModeNearest = new Chart(ctx, { - type: 'line', - data: data, -}); - -// This chart would have the hover mode that was passed in -var chartDifferentHoverMode = new Chart(ctx, { - type: 'line', - data: data, - options: { - hover: { - // Overrides the global setting - mode: 'index' - } - } -}) -``` - -#### Global Font Settings - -There are 4 special global settings that can change all of the fonts on the chart. These options are in `Chart.defaults.global`. - -Name | Type | Default | Description ---- | --- | --- | --- -defaultFontColor | Color | '#666' | Default font color for all text -defaultFontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Default font family for all text -defaultFontSize | Number | 12 | Default font size (in px) for text. Does not apply to radialLinear scale point labels -defaultFontStyle | String | 'normal' | Default font style. Does not apply to tooltip title or footer. Does not apply to chart title - -### Common Chart Configuration - -The following options are applicable to all charts. The can be set on the [global configuration](#chart-configuration-global-configuration), or they can be passed to the chart constructor. - -Name | Type | Default | Description ---- | --- | --- | --- -responsive | Boolean | true | Resizes the chart canvas when its container does. -responsiveAnimationDuration | Number | 0 | Duration in milliseconds it takes to animate to new size after a resize event. -maintainAspectRatio | Boolean | true | Maintain the original canvas aspect ratio `(width / height)` when resizing -events | Array[String] | `["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"]` | Events that the chart should listen to for tooltips and hovering -onClick | Function | null | Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed the event and an array of active elements -legendCallback | Function | ` function (chart) { }` | Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string. -onResize | Function | null | Called when a resize occurs. Gets passed two arguments: the chart instance and the new size. - -### Layout Configuration - -The layout configuration is passed into the `options.layout` namespace. The global options for the chart layout is defined in `Chart.defaults.global.layout`. - -Name | Type | Default | Description ---- | --- | --- | --- -padding | Number or Object | 0 | The padding to add inside the chart. If this value is a number, it is applied to all sides of the chart (left, top, right, bottom). If this value is an object, the `left` property defines the left padding. Similarly the `right`, `top`, and `bottom` properties can also be specified. - - -### Title Configuration - -The title configuration is passed into the `options.title` namespace. The global options for the chart title is defined in `Chart.defaults.global.title`. - -Name | Type | Default | Description ---- | --- | --- | --- -display | Boolean | false | Display the title block -position | String | 'top' | Position of the title. Possible values are 'top', 'left', 'bottom' and 'right'. -fullWidth | Boolean | true | Marks that this box should take the full width of the canvas (pushing down other boxes) -fontSize | Number | 12 | Font size inherited from global configuration -fontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family inherited from global configuration -fontColor | Color | "#666" | Font color inherited from global configuration -fontStyle | String | 'bold' | Font styling of the title. -padding | Number | 10 | Number of pixels to add above and below the title text -text | String | '' | Title text - -#### Example Usage - -The example below would enable a title of 'Custom Chart Title' on the chart that is created. - -```javascript -var chart = new Chart(ctx, { - type: 'line', - data: data, - options: { - title: { - display: true, - text: 'Custom Chart Title' - } - } -}) -``` - -### Legend Configuration - -The legend configuration is passed into the `options.legend` namespace. The global options for the chart legend is defined in `Chart.defaults.global.legend`. - -Name | Type | Default | Description ---- | --- | --- | --- -display | Boolean | true | Is the legend displayed -position | String | 'top' | Position of the legend. Possible values are 'top', 'left', 'bottom' and 'right'. -fullWidth | Boolean | true | Marks that this box should take the full width of the canvas (pushing down other boxes) -onClick | Function | `function(event, legendItem) {}` | A callback that is called when a 'click' event is registered on top of a label item -onHover | Function | `function(event, legendItem) {}` | A callback that is called when a 'mousemove' event is registered on top of a label item -labels |Object|-| See the [Legend Label Configuration](#chart-configuration-legend-label-configuration) section below. -reverse | Boolean | false | Legend will show datasets in reverse order - -#### Legend Label Configuration - -The legend label configuration is nested below the legend configuration using the `labels` key. - -Name | Type | Default | Description ---- | --- | --- | --- -boxWidth | Number | 40 | Width of coloured box -fontSize | Number | 12 | Font size inherited from global configuration -fontStyle | String | "normal" | Font style inherited from global configuration -fontColor | Color | "#666" | Font color inherited from global configuration -fontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family inherited from global configuration -padding | Number | 10 | Padding between rows of colored boxes -generateLabels: | Function | `function(chart) { }` | Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See [Legend Item](#chart-configuration-legend-item-interface) for details. -filter | Function | null | Filters legend items out of the legend. Receives 2 parameters, a [Legend Item](#chart-configuration-legend-item-interface) and the chart data -usePointStyle | Boolean | false | Label style will match corresponding point style (size is based on fontSize, boxWidth is not used in this case). - -#### Legend Item Interface - -Items passed to the legend `onClick` function are the ones returned from `labels.generateLabels`. These items must implement the following interface. - -```javascript -{ - // Label that will be displayed - text: String, - - // Fill style of the legend box - fillStyle: Color, - - // If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect - hidden: Boolean, - - // For box border. See https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap - lineCap: String, - - // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash - lineDash: Array[Number], - - // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset - lineDashOffset: Number, - - // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin - lineJoin: String, - - // Width of box border - lineWidth: Number, - - // Stroke style of the legend box - strokeStyle: Color - - // Point style of the legend box (only used if usePointStyle is true) - pointStyle: String -} -``` - -#### Example - -The following example will create a chart with the legend enabled and turn all of the text red in color. - -```javascript -var chart = new Chart(ctx, { - type: 'bar', - data: data, - options: { - legend: { - display: true, - labels: { - fontColor: 'rgb(255, 99, 132)' - } - } -} -}); -``` - -### Tooltip Configuration - -The tooltip configuration is passed into the `options.tooltips` namespace. The global options for the chart tooltips is defined in `Chart.defaults.global.tooltips`. - -Name | Type | Default | Description ---- | --- | --- | --- -enabled | Boolean | true | Are tooltips enabled -custom | Function | null | See [section](#advanced-usage-external-tooltips) below -mode | String | 'nearest' | Sets which elements appear in the tooltip. See [Interaction Modes](#interaction-modes) for details -intersect | Boolean | true | if true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times. -position | String | 'average' | The mode for positioning the tooltip. 'average' mode will place the tooltip at the average position of the items displayed in the tooltip. 'nearest' will place the tooltip at the position of the element closest to the event position. New modes can be defined by adding functions to the Chart.Tooltip.positioners map. -itemSort | Function | undefined | Allows sorting of [tooltip items](#chart-configuration-tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). This function can also accept a third parameter that is the data object passed to the chart. -filter | Function | undefined | Allows filtering of [tooltip items](#chart-configuration-tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.filter](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). This function can also accept a second parameter that is the data object passed to the chart. -backgroundColor | Color | 'rgba(0,0,0,0.8)' | Background color of the tooltip -titleFontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family for tooltip title inherited from global font family -titleFontSize | Number | 12 | Font size for tooltip title inherited from global font size -titleFontStyle | String | "bold" | -titleFontColor | Color | "#fff" | Font color for tooltip title -titleSpacing | Number | 2 | Spacing to add to top and bottom of each title line. -titleMarginBottom | Number | 6 | Margin to add on bottom of title section -bodyFontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family for tooltip items inherited from global font family -bodyFontSize | Number | 12 | Font size for tooltip items inherited from global font size -bodyFontStyle | String | "normal" | -bodyFontColor | Color | "#fff" | Font color for tooltip items. -bodySpacing | Number | 2 | Spacing to add to top and bottom of each tooltip item -footerFontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family for tooltip footer inherited from global font family. -footerFontSize | Number | 12 | Font size for tooltip footer inherited from global font size. -footerFontStyle | String | "bold" | Font style for tooltip footer. -footerFontColor | Color | "#fff" | Font color for tooltip footer. -footerSpacing | Number | 2 | Spacing to add to top and bottom of each footer line. -footerMarginTop | Number | 6 | Margin to add before drawing the footer -xPadding | Number | 6 | Padding to add on left and right of tooltip -yPadding | Number | 6 | Padding to add on top and bottom of tooltip -caretSize | Number | 5 | Size, in px, of the tooltip arrow -cornerRadius | Number | 6 | Radius of tooltip corner curves -multiKeyBackground | Color | "#fff" | Color to draw behind the colored boxes when multiple items are in the tooltip -displayColors | Boolean | true | if true, color boxes are shown in the tooltip -callbacks | Object | | See the [callbacks section](#chart-configuration-tooltip-callbacks) below -borderColor | Color | 'rgba(0,0,0,0)' | Color of the border -borderWidth | Number | 0 | Size of the border - -#### Tooltip Callbacks - -The tooltip label configuration is nested below the tooltip configuration using the `callbacks` key. The tooltip has the following callbacks for providing text. For all functions, 'this' will be the tooltip object created from the Chart.Tooltip constructor. - -All functions are called with the same arguments: a [tooltip item](#chart-configuration-tooltip-item-interface) and the data object passed to the chart. All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text. - -Callback | Arguments | Description ---- | --- | --- -beforeTitle | `Array[tooltipItem], data` | Text to render before the title -title | `Array[tooltipItem], data` | Text to render as the title -afterTitle | `Array[tooltipItem], data` | Text to render after the title -beforeBody | `Array[tooltipItem], data` | Text to render before the body section -beforeLabel | `tooltipItem, data` | Text to render before an individual label -label | `tooltipItem, data` | Text to render for an individual item in the tooltip -labelColor | `tooltipItem, chart` | Returns the colors to render for the tooltip item. Return as an object containing two parameters: `borderColor` and `backgroundColor`. -afterLabel | `tooltipItem, data` | Text to render after an individual label -afterBody | `Array[tooltipItem], data` | Text to render after the body section -beforeFooter | `Array[tooltipItem], data` | Text to render before the footer section -footer | `Array[tooltipItem], data` | Text to render as the footer -afterFooter | `Array[tooltipItem], data` | Text to render after the footer section -dataPoints | `Array[tooltipItem]` | List of matching point informations. - -#### Tooltip Item Interface - -The tooltip items passed to the tooltip callbacks implement the following interface. - -```javascript -{ - // X Value of the tooltip as a string - xLabel: String, - - // Y value of the tooltip as a string - yLabel: String, - - // Index of the dataset the item comes from - datasetIndex: Number, - - // Index of this data item in the dataset - index: Number, - - // X position of matching point - x: Number, - - // Y position of matching point - y: Number, -} -``` - -### Hover Configuration - -The hover configuration is passed into the `options.hover` namespace. The global hover configuration is at `Chart.defaults.global.hover`. - -Name | Type | Default | Description ---- | --- | --- | --- -mode | String | 'nearest' | Sets which elements appear in the tooltip. See [Interaction Modes](#interaction-modes) for details -intersect | Boolean | true | if true, the hover mode only applies when the mouse position intersects an item on the chart -animationDuration | Number | 400 | Duration in milliseconds it takes to animate hover style changes -onHover | Function | null | Called when any of the events fire. Called in the context of the chart and passed the event and an array of active elements (bars, points, etc) - -### Interaction Modes -When configuring interaction with the graph via hover or tooltips, a number of different modes are available. - -The following table details the modes and how they behave in conjunction with the `intersect` setting - -Mode | Behaviour ---- | --- -point | Finds all of the items that intersect the point -nearest | Gets the item that is nearest to the point. The nearest item is determined based on the distance to the center of the chart item (point, bar). If 2 or more items are at the same distance, the one with the smallest area is used. If `intersect` is true, this is only triggered when the mouse position intersects an item in the graph. This is very useful for combo charts where points are hidden behind bars. -single (deprecated) | Finds the first item that intersects the point and returns it. Behaves like 'nearest' mode with intersect = true. -label (deprecated) | See `'index'` mode -index | Finds item at the same index. If the `intersect` setting is true, the first intersecting item is used to determine the index in the data. If `intersect` false the nearest item is used to determine the index. -x-axis (deprecated) | Behaves like `'index'` mode with `intersect = false` -dataset | Finds items in the same dataset. If the `intersect` setting is true, the first intersecting item is used to determine the index in the data. If `intersect` false the nearest item is used to determine the index. -x | Returns all items that would intersect based on the `X` coordinate of the position only. Would be useful for a vertical cursor implementation. Note that this only applies to cartesian charts -y | Returns all items that would intersect based on the `Y` coordinate of the position. This would be useful for a horizontal cursor implementation. Note that this only applies to cartesian charts. - -### Animation Configuration - -The following animation options are available. The global options for are defined in `Chart.defaults.global.animation`. - -Name | Type | Default | Description ---- |:---:| --- | --- -duration | Number | 1000 | The number of milliseconds an animation takes. -easing | String | "easeOutQuart" | Easing function to use. Available options are: `'linear'`, `'easeInQuad'`, `'easeOutQuad'`, `'easeInOutQuad'`, `'easeInCubic'`, `'easeOutCubic'`, `'easeInOutCubic'`, `'easeInQuart'`, `'easeOutQuart'`, `'easeInOutQuart'`, `'easeInQuint'`, `'easeOutQuint'`, `'easeInOutQuint'`, `'easeInSine'`, `'easeOutSine'`, `'easeInOutSine'`, `'easeInExpo'`, `'easeOutExpo'`, `'easeInOutExpo'`, `'easeInCirc'`, `'easeOutCirc'`, `'easeInOutCirc'`, `'easeInElastic'`, `'easeOutElastic'`, `'easeInOutElastic'`, `'easeInBack'`, `'easeOutBack'`, `'easeInOutBack'`, `'easeInBounce'`, `'easeOutBounce'`, `'easeInOutBounce'`. See [Robert Penner's easing equations](http://robertpenner.com/easing/). -onProgress | Function | none | Callback called on each step of an animation. Passed a single argument, a `Chart.Animation` instance, see below. -onComplete | Function | none | Callback called at the end of an animation. Passed a single argument, a `Chart.Animation` instance, see below. - -#### Animation Callbacks - -The `onProgress` and `onComplete` callbacks are useful for synchronizing an external draw to the chart animation. The callback is passed a `Chart.Animation` instance: - -```javascript -{ - // Chart instance - chart, - - // Current Animation frame number - currentStep: Number, - - // Number of animation frames - numSteps: Number, - - // Animation easing to use - easing: String, - - // Function that renders the chart - render: Function, - - // User callback - onAnimationProgress: Function, - - // User callback - onAnimationComplete: Function -} -``` - -An example usage of these callbacks can be found on [Github](https://github.com/chartjs/Chart.js/blob/master/samples/animation/progress-bar.html): this sample displays a progress bar showing how far along the animation is. - -### Element Configuration - -The global options for elements are defined in `Chart.defaults.global.elements`. - -Options can be configured for four different types of elements: arc, lines, points, and rectangles. When set, these options apply to all objects of that type unless specifically overridden by the configuration attached to a dataset. - -#### Arc Configuration - -Arcs are used in the polar area, doughnut and pie charts. They can be configured with the following options. The global arc options are stored in `Chart.defaults.global.elements.arc`. - -Name | Type | Default | Description ---- | --- | --- | --- -backgroundColor | Color | 'rgba(0,0,0,0.1)' | Default fill color for arcs. Inherited from the global default -borderColor | Color | '#fff' | Default stroke color for arcs -borderWidth | Number | 2 | Default stroke width for arcs - -#### Line Configuration - -Line elements are used to represent the line in a line chart. The global line options are stored in `Chart.defaults.global.elements.line`. - -Name | Type | Default | Description ---- | --- | --- | --- -tension | Number | 0.4 | Default bezier curve tension. Set to `0` for no bezier curves. -backgroundColor | Color | 'rgba(0,0,0,0.1)' | Default line fill color -borderWidth | Number | 3 | Default line stroke width -borderColor | Color | 'rgba(0,0,0,0.1)' | Default line stroke color -borderCapStyle | String | 'butt' | Default line cap style. See [MDN](https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap) -borderDash | Array | `[]` | Default line dash. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash) -borderDashOffset | Number | 0.0 | Default line dash offset. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset) -borderJoinStyle | String | 'miter' | Default line join style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin) -capBezierPoints | Boolean | true | If true, bezier control points are kept inside the chart. If false, no restriction is enforced. -fill | Boolean or String | true | If true, the fill is assumed to be to zero. String values are 'zero', 'top', and 'bottom' to fill to different locations. If `false`, no fill is added -stepped | Boolean | false | If true, the line is shown as a stepped line and 'tension' will be ignored - -#### Point Configuration - -Point elements are used to represent the points in a line chart or a bubble chart. The global point options are stored in `Chart.defaults.global.elements.point`. - -Name | Type | Default | Description ---- | --- | --- | --- -radius | Number | 3 | Default point radius -pointStyle | String | 'circle' | Default point style -backgroundColor | Color | 'rgba(0,0,0,0.1)' | Default point fill color -borderWidth | Number | 1 | Default point stroke width -borderColor | Color | 'rgba(0,0,0,0.1)' | Default point stroke color -hitRadius | Number | 1 | Extra radius added to point radius for hit detection -hoverRadius | Number | 4 | Default point radius when hovered -hoverBorderWidth | Number | 1 | Default stroke width when hovered - -#### Rectangle Configuration - -Rectangle elements are used to represent the bars in a bar chart. The global rectangle options are stored in `Chart.defaults.global.elements.rectangle`. - -Name | Type | Default | Description ---- | --- | --- | --- -backgroundColor | Color | 'rgba(0,0,0,0.1)' | Default bar fill color -borderWidth | Number | 0 | Default bar stroke width -borderColor | Color | 'rgba(0,0,0,0.1)' | Default bar stroke color -borderSkipped | String | 'bottom' | Default skipped (excluded) border for rectangle. Can be one of `bottom`, `left`, `top`, `right` - -### Colors - -When supplying colors to Chart options, you can use a number of formats. You can specify the color as a string in hexadecimal, RGB, or HSL notations. If a color is needed, but not specified, Chart.js will use the global default color. This color is stored at `Chart.defaults.global.defaultColor`. It is initially set to 'rgba(0, 0, 0, 0.1)'; - -You can also pass a [CanvasGradient](https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient) object. You will need to create this before passing to the chart, but using it you can achieve some interesting effects. - -### Patterns - -An alternative option is to pass a [CanvasPattern](https://developer.mozilla.org/en-US/docs/Web/API/CanvasPattern) object. For example, if you wanted to fill a dataset with a pattern from an image you could do the following. - -```javascript -var img = new Image(); -img.src = 'https://example.com/my_image.png'; -img.onload = function() { - var ctx = document.getElementById('canvas').getContext('2d'); - var fillPattern = ctx.createPattern(img, 'repeat'); - - var chart = new Chart(ctx, { - data: { - labels: ['Item 1', 'Item 2', 'Item 3'], - datasets: [{ - data: [10, 20, 30], - backgroundColor: fillPattern - }] - } - }) -} -``` - -Using pattern fills for data graphics can help viewers with vision deficiencies (e.g. color-blindness or partial sight) to [more easily understand your data](http://betweentwobrackets.com/data-graphics-and-colour-vision/). - -Using the [Patternomaly](https://github.com/ashiguruma/patternomaly) library you can generate patterns to fill datasets. - -```javascript -var chartData = { - datasets: [{ - data: [45, 25, 20, 10], - backgroundColor: [ - pattern.draw('square', '#ff6384'), - pattern.draw('circle', '#36a2eb'), - pattern.draw('diamond', '#cc65fe'), - pattern.draw('triangle', '#ffce56'), - ] - }], - labels: ['Red', 'Blue', 'Purple', 'Yellow'] -}; -``` - -### Mixed Chart Types - -When creating a chart, you have the option to overlay different chart types on top of each other as separate datasets. - -To do this, you must set a `type` for each dataset individually. You can create mixed chart types with bar and line chart types. - -When creating the chart you must set the overall `type` as `bar`. - -```javascript -var myChart = new Chart(ctx, { - type: 'bar', - data: { - labels: ['Item 1', 'Item 2', 'Item 3'], - datasets: [ - { - type: 'bar', - label: 'Bar Component', - data: [10, 20, 30], - }, - { - type: 'line', - label: 'Line Component', - data: [30, 20, 10], - } - ] - } -}); -```
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
docs/02-Scales.md
@@ -1,370 +0,0 @@ ---- -title: Scales -anchor: scales ---- - -Scales in v2.0 of Chart.js are significantly more powerful, but also different than those of v1.0. -* Multiple X & Y axes are supported. -* A built-in label auto-skip feature detects would-be overlapping ticks and labels and removes every nth label to keep things displaying normally. -* Scale titles are supported -* New scale types can be extended without writing an entirely new chart type - - -### Common Configuration - -Every scale extends a core scale class with the following options: - -Name | Type | Default | Description ---- | --- | --- | --- -type | String | Chart specific. | Type of scale being employed. Custom scales can be created and registered with a string key. Options: ["category"](#scales-category-scale), ["linear"](#scales-linear-scale), ["logarithmic"](#scales-logarithmic-scale), ["time"](#scales-time-scale), ["radialLinear"](#scales-radial-linear-scale) -display | Boolean | true | If true, show the scale including gridlines, ticks, and labels. Overrides *gridLines.display*, *scaleLabel.display*, and *ticks.display*. -position | String | "left" | Position of the scale. Possible values are 'top', 'left', 'bottom' and 'right'. -id | String | | The ID is used to link datasets and scale axes together. The properties `datasets.xAxisID` or `datasets.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used. -beforeUpdate | Function | undefined | Callback called before the update process starts. Passed a single argument, the scale instance. -beforeSetDimensions | Function | undefined | Callback that runs before dimensions are set. Passed a single argument, the scale instance. -afterSetDimensions | Function | undefined | Callback that runs after dimensions are set. Passed a single argument, the scale instance. -beforeDataLimits | Function | undefined | Callback that runs before data limits are determined. Passed a single argument, the scale instance. -afterDataLimits | Function | undefined | Callback that runs after data limits are determined. Passed a single argument, the scale instance. -beforeBuildTicks | Function | undefined | Callback that runs before ticks are created. Passed a single argument, the scale instance. -afterBuildTicks | Function | undefined | Callback that runs after ticks are created. Useful for filtering ticks. Passed a single argument, the scale instance. -beforeTickToLabelConversion | Function | undefined | Callback that runs before ticks are converted into strings. Passed a single argument, the scale instance. -afterTickToLabelConversion | Function | undefined | Callback that runs after ticks are converted into strings. Passed a single argument, the scale instance. -beforeCalculateTickRotation | Function | undefined | Callback that runs before tick rotation is determined. Passed a single argument, the scale instance. -afterCalculateTickRotation | Function | undefined | Callback that runs after tick rotation is determined. Passed a single argument, the scale instance. -beforeFit | Function | undefined | Callback that runs before the scale fits to the canvas. Passed a single argument, the scale instance. -afterFit | Function | undefined | Callback that runs after the scale fits to the canvas. Passed a single argument, the scale instance. -afterUpdate | Function | undefined | Callback that runs at the end of the update process. Passed a single argument, the scale instance. -**gridLines** | Object | - | See [grid line configuration](#grid-line-configuration) section. -**scaleLabel** | Object | | See [scale title configuration](#scale-title-configuration) section. -**ticks** | Object | | See [tick configuration](#tick-configuration) section. - -#### Grid Line Configuration - -The grid line configuration is nested under the scale configuration in the `gridLines` key. It defines options for the grid lines that run perpendicular to the axis. - -Name | Type | Default | Description ---- | --- | --- | --- -display | Boolean | true | -color | Color or Array[Color] | "rgba(0, 0, 0, 0.1)" | Color of the grid lines. -borderDash | Array[Number] | [] | Length and spacing of dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash) -borderDashOffset | Number | 0.0 | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset) -lineWidth | Number or Array[Number] | 1 | Stroke width of grid lines -drawBorder | Boolean | true | If true draw border on the edge of the chart -drawOnChartArea | Boolean | true | If true, draw lines on the chart area inside the axis lines. This is useful when there are multiple axes and you need to control which grid lines are drawn -drawTicks | Boolean | true | If true, draw lines beside the ticks in the axis area beside the chart. -tickMarkLength | Number | 10 | Length in pixels that the grid lines will draw into the axis area. -zeroLineWidth | Number | 1 | Stroke width of the grid line for the first index (index 0). -zeroLineColor | Color | "rgba(0, 0, 0, 0.25)" | Stroke color of the grid line for the first index (index 0). -offsetGridLines | Boolean | false | If true, labels are shifted to be between grid lines. This is used in the bar chart. - -#### Scale Title Configuration - -The scale label configuration is nested under the scale configuration in the `scaleLabel` key. It defines options for the scale title. - -Name | Type | Default | Description ---- | --- | --- | --- -display | Boolean | false | -labelString | String | "" | The text for the title. (i.e. "# of People", "Response Choices") -fontColor | Color | "#666" | Font color for the scale title. -fontFamily| String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family for the scale title, follows CSS font-family options. -fontSize | Number | 12 | Font size for the scale title. -fontStyle | String | "normal" | Font style for the scale title, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). - -#### Tick Configuration - -The tick configuration is nested under the scale configuration in the `ticks` key. It defines options for the tick marks that are generated by the axis. - -Name | Type | Default | Description ---- | --- | --- | --- -autoSkip | Boolean | true | If true, automatically calculates how many labels that can be shown and hides labels accordingly. Turn it off to show all labels no matter what -autoSkipPadding | Number | 0 | Padding between the ticks on the horizontal axis when `autoSkip` is enabled. *Note: Only applicable to horizontal scales.* -callback | Function | `function(value) { return helpers.isArray(value) ? value : '' + value; }` | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](#scales-creating-custom-tick-formats) section below. -display | Boolean | true | If true, show the ticks. -fontColor | Color | "#666" | Font color for the tick labels. -fontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family for the tick labels, follows CSS font-family options. -fontSize | Number | 12 | Font size for the tick labels. -fontStyle | String | "normal" | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). -labelOffset | Number | 0 | Distance in pixels to offset the label from the centre point of the tick (in the y direction for the x axis, and the x direction for the y axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas* -maxRotation | Number | 90 | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.* -minRotation | Number | 0 | Minimum rotation for tick labels. *Note: Only applicable to horizontal scales.* -mirror | Boolean | false | Flips tick labels around axis, displaying the labels inside the chart instead of outside. *Note: Only applicable to vertical scales.* -padding | Number | 10 | Padding between the tick label and the axis. *Note: Only applicable to horizontal scales.* -reverse | Boolean | false | Reverses order of tick labels. - -#### Creating Custom Tick Formats - -The `callback` method may be used for advanced tick customization. In the following example, every label of the Y axis would be displayed in scientific notation. - -If the callback returns `null` or `undefined` the associated grid line will be hidden. - -```javascript -var chart = new Chart(ctx, { - type: 'line', - data: data, - options: { - scales: { - yAxes: [{ - ticks: { - // Create scientific notation labels - callback: function(value, index, values) { - return value.toExponential(); - } - } - }] - } - } -}); -``` - -### Category Scale - -The category scale will be familiar to those who have used v1.0. Labels are drawn from one of the label arrays included in the chart data. If only `data.labels` is defined, this will be used. If `data.xLabels` is defined and the axis is horizontal, this will be used. Similarly, if `data.yLabels` is defined and the axis is vertical, this property will be used. Using both `xLabels` and `yLabels` together can create a chart that uses strings for both the X and Y axes. - -#### Configuration Options - -The category scale has the following additional options that can be set. - -Name | Type | Default | Description ---- | --- | --- | --- -ticks.min | String | - | The minimum item to display. Must be a value in the `labels` array -ticks.max | String | - | The maximum item to display. Must be a value in the `labels` array - -### Linear Scale - -The linear scale is use to chart numerical data. It can be placed on either the x or y axis. The scatter chart type automatically configures a line chart to use one of these scales for the x axis. As the name suggests, linear interpolation is used to determine where a value lies on the axis. - -#### Configuration Options - -The following options are provided by the linear scale. They are all located in the `ticks` sub options. - -Name | Type | Default | Description ---- | --- | --- | --- -beginAtZero | Boolean | - | if true, scale will include 0 if it is not already included. -min | Number | - | User defined minimum number for the scale, overrides minimum value from data. -max | Number | - | User defined maximum number for the scale, overrides maximum value from data. -maxTicksLimit | Number | 11 | Maximum number of ticks and gridlines to show. If not defined, it will limit to 11 ticks but will show all gridlines. -fixedStepSize | Number | - | User defined fixed step size for the scale. If set, the scale ticks will be enumerated by multiple of stepSize, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm. -stepSize | Number | - | if defined, it can be used along with the min and the max to give a custom number of steps. See the example below. -suggestedMax | Number | - | User defined maximum number for the scale, overrides maximum value *except for if* it is lower than the maximum value. -suggestedMin | Number | - | User defined minimum number for the scale, overrides minimum value *except for if* it is higher than the minimum value. - -#### Example Configuration - -The following example creates a line chart with a vertical axis that goes from 0 to 5 in 0.5 sized steps. - -```javascript -var chart = new Chart(ctx, { - type: 'line', - data: data, - options: { - scales: { - yAxes: [{ - ticks: { - max: 5, - min: 0, - stepSize: 0.5 - } - }] - } - } -}); -``` - -### Logarithmic Scale - -The logarithmic scale is use to chart numerical data. It can be placed on either the x or y axis. As the name suggests, logarithmic interpolation is used to determine where a value lies on the axis. - -#### Configuration Options - -The following options are provided by the logarithmic scale. They are all located in the `ticks` sub options. - -Name | Type | Default | Description ---- | --- | --- | --- -min | Number | - | User defined minimum number for the scale, overrides minimum value from data. -max | Number | - | User defined maximum number for the scale, overrides maximum value from data. - -#### Example Configuration - -The following example creates a chart with a logarithmic X axis that ranges from 1 to 1000. - -```javascript -var chart = new Chart(ctx, { - type: 'line', - data: data, - options: { - scales: { - xAxes: [{ - type: 'logarithmic', - position: 'bottom', - ticks: { - min: 1, - max: 1000 - } - }] - } - } -}) -``` - -### Time Scale - -The time scale is used to display times and dates. It can only be placed on the X axis. When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale. - -#### Configuration Options - -The following options are provided by the time scale. They are all located in the `time` sub options. - -Name | Type | Default | Description ---- | --- | --- | --- -displayFormats | Object | - | See [Display Formats](#scales-display-formats) section below. -isoWeekday | Boolean | false | If true and the unit is set to 'week', iso weekdays will be used. -max | [Time](#scales-date-formats) | - | If defined, this will override the data maximum -min | [Time](#scales-date-formats) | - | If defined, this will override the data minimum -parser | String or Function | - | If defined as a string, it is interpreted as a custom format to be used by moment to parse the date. If this is a function, it must return a moment.js object given the appropriate data value. -round | String | - | If defined, dates will be rounded to the start of this unit. See [Time Units](#scales-time-units) below for the allowed units. -tooltipFormat | String | '' | The moment js format string to use for the tooltip. -unit | String | - | If defined, will force the unit to be a certain type. See [Time Units](#scales-time-units) section below for details. -unitStepSize | Number | 1 | The number of units between grid lines. -minUnit | String | 'millisecond' | The minimum display format to be used for a time unit - -#### Date Formats - -When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See [Moment.js docs](http://momentjs.com/docs/#/parsing/) for details. - -#### Display Formats - -The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [moment.js](http://momentjs.com/docs/#/displaying/format/) for the allowable format strings. - -Name | Default ---- | --- -millisecond | 'SSS [ms]' -second | 'h:mm:ss a' -minute | 'h:mm:ss a' -hour | 'MMM D, hA' -day | 'll' -week | 'll' -month | 'MMM YYYY' -quarter | '[Q]Q - YYYY' -year | 'YYYY' - -For example, to set the display format for the 'quarter' unit to show the month and year, the following config would be passed to the chart constructor. - -```javascript -var chart = new Chart(ctx, { - type: 'line', - data: data, - options: { - scales: { - xAxes: [{ - type: 'time', - time: { - displayFormats: { - quarter: 'MMM YYYY' - } - } - }] - } - } -}) -``` - -#### Time Units - -The following time measurements are supported. The names can be passed as strings to the `time.unit` config option to force a certain unit. - -* millisecond -* second -* minute -* hour -* day -* week -* month -* quarter -* year - -For example, to create a chart with a time scale that always displayed units per month, the following config could be used. - -```javascript -var chart = new Chart(ctx, { - type: 'line', - data: data, - options: { - scales: { - xAxes: [{ - time: { - unit: 'month' - } - }] - } - } -}) -``` - -### Radial Linear Scale - -The radial linear scale is used specifically for the radar and polar area chart types. It overlays the chart area, rather than being positioned on one of the edges. - -#### Configuration Options - -The following additional configuration options are provided by the radial linear scale. - -Name | Type | Default | Description ---- | --- | --- | --- -*gridLines*.circular | Boolean | false | if true, radial lines are circular. If false, they are straight lines connecting the the different angle line locations. -angleLines | Object | - | See the Angle Line Options section below for details. -pointLabels | Object | - | See the Point Label Options section below for details. -ticks | Object | - | See the Ticks table below for options. - -#### Angle Line Options - -The following options are used to configure angled lines that radiate from the center of the chart to the point labels. They can be found in the `angleLines` sub options. Note that these options only apply if `angleLines.display` is true. - -Name | Type | Default | Description ---- | --- | --- | --- -display | Boolean | true | If true, angle lines are shown. -color | Color | 'rgba(0, 0, 0, 0.1)' | Color of angled lines -lineWidth | Number | 1 | Width of angled lines - -#### Point Label Options - -The following options are used to configure the point labels that are shown on the perimeter of the scale. They can be found in the `pointLabels` sub options. Note that these options only apply if `pointLabels.display` is true. - -Name | Type | Default | Description ---- | --- | --- | --- -display | Boolean | true | If true, point labels are shown -callback | Function | - | Callback function to transform data label to axis label -fontColor | Color | '#666' | Font color -fontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family to render -fontSize | Number | 10 | Font size in pixels -fontStyle | String | 'normal' | Font Style to use - - -#### Tick Options - -Name | Type | Default | Description ---- | --- | --- | --- -backdropColor | Color | 'rgba(255, 255, 255, 0.75)' | Color of label backdrops -backdropPaddingX | Number | 2 | Horizontal padding of label backdrop -backdropPaddingY | Number | 2 | Vertical padding of label backdrop -beginAtZero | Boolean | - | if true, scale will include 0 if it is not already included. -min | Number | - | User defined minimum number for the scale, overrides minimum value from data. -max | Number | - | User defined maximum number for the scale, overrides maximum value from data. -maxTicksLimit | Number | 11 | Maximum number of ticks and gridlines to show. If not defined, it will limit to 11 ticks but will show all gridlines. -showLabelBackdrop | Boolean | true | If true, draw a background behind the tick labels -fixedStepSize | Number | - | User defined fixed step size for the scale. If set, the scale ticks will be enumerated by multiple of stepSize, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm. -stepSize | Number | - | if defined, it can be used along with the min and the max to give a custom number of steps. See the example below. -suggestedMax | Number | - | User defined maximum number for the scale, overrides maximum value *except for if* it is lower than the maximum value. -suggestedMin | Number | - | User defined minimum number for the scale, overrides minimum value *except for if* it is higher than the minimum value. - -### Update Default Scale config - -The default configuration for a scale can be easily changed using the scale service. Pass in a partial configuration that will be merged with the current scale default configuration. - -For example, to set the minimum value of 0 for all linear scales, you would do the following. Any linear scales created after this time would now have a minimum of 0. -``` -Chart.scaleService.updateScaleDefaults('linear', { - ticks: { - min: 0 - } -}) -```
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
docs/03-Line-Chart.md
@@ -1,187 +0,0 @@ ---- -title: Line Chart -anchor: line-chart ---- -### Introduction -A line chart is a way of plotting data points on a line. Often, it is used to show trend data, and the comparison of two data sets. - -<div class="canvas-holder"> - <canvas width="250" height="125"></canvas> -</div> - -### Example Usage -```javascript -var myLineChart = new Chart(ctx, { - type: 'line', - data: data, - options: options -}); -``` - -Alternatively a line chart can be created using syntax similar to the v1.0 syntax -```javascript -var myLineChart = Chart.Line(ctx, { - data: data, - options: options -}); -``` - -### Dataset Structure - -The following options can be included in a line chart dataset to configure options for that specific dataset. - -All point* properties can be specified as an array. If these are set to an array value, the first value applies to the first point, the second value to the second point, and so on. - -Property | Type | Usage ---- | --- | --- -data | See [data point](#line-chart-data-points) section | The data to plot in a line -label | `String` | The label for the dataset which appears in the legend and tooltips -xAxisID | `String` | The ID of the x axis to plot this dataset on -yAxisID | `String` | The ID of the y axis to plot this dataset on -fill | `Boolean` | If true, fill the area under the line -cubicInterpolationMode | `String` | Algorithm used to interpolate a smooth curve from the discrete data points. Options are 'default' and 'monotone'. The 'default' algorithm uses a custom weighted cubic interpolation, which produces pleasant curves for all types of datasets. The 'monotone' algorithm is more suited to `y = f(x)` datasets : it preserves monotonicity (or piecewise monotonicity) of the dataset being interpolated, and ensures local extremums (if any) stay at input data points. If left untouched (`undefined`), the global `options.elements.line.cubicInterpolationMode` property is used. -lineTension | `Number` | Bezier curve tension of the line. Set to 0 to draw straightlines. This option is ignored if monotone cubic interpolation is used. *Note* This was renamed from 'tension' but the old name still works. -backgroundColor | `Color` | The fill color under the line. See [Colors](#chart-configuration-colors) -borderWidth | `Number` | The width of the line in pixels -borderColor | `Color` | The color of the line. -borderCapStyle | `String` | Cap style of the line. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap) -borderDash | `Array<Number>` | Length and spacing of dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash) -borderDashOffset | `Number` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset) -borderJoinStyle | `String` | Line joint style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin) -pointBorderColor | `Color or Array<Color>` | The border color for points. -pointBackgroundColor | `Color or Array<Color>` | The fill color for points -pointBorderWidth | `Number or Array<Number>` | The width of the point border in pixels -pointRadius | `Number or Array<Number>` | The radius of the point shape. If set to 0, nothing is rendered. -pointHoverRadius | `Number or Array<Number>` | The radius of the point when hovered -pointHitRadius | `Number or Array<Number>` | The pixel size of the non-displayed point that reacts to mouse events -pointHoverBackgroundColor | `Color or Array<Color>` | Point background color when hovered -pointHoverBorderColor | `Color or Array<Color>` | Point border color when hovered -pointHoverBorderWidth | `Number or Array<Number>` | Border width of point when hovered -pointStyle | `String, Array<String>, Image, Array<Image>` | The style of point. Options are 'circle', 'triangle', 'rect', 'rectRounded', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash'. If the option is an image, that image is drawn on the canvas using `drawImage`. -showLine | `Boolean` | If false, the line is not drawn for this dataset -spanGaps | `Boolean` | If true, lines will be drawn between points with no or null data -steppedLine | `Boolean` | If true, the line is shown as a stepped line and 'lineTension' will be ignored - -An example data object using these attributes is shown below. -```javascript -var data = { - labels: ["January", "February", "March", "April", "May", "June", "July"], - datasets: [ - { - label: "My First dataset", - fill: false, - lineTension: 0.1, - backgroundColor: "rgba(75,192,192,0.4)", - borderColor: "rgba(75,192,192,1)", - borderCapStyle: 'butt', - borderDash: [], - borderDashOffset: 0.0, - borderJoinStyle: 'miter', - pointBorderColor: "rgba(75,192,192,1)", - pointBackgroundColor: "#fff", - pointBorderWidth: 1, - pointHoverRadius: 5, - pointHoverBackgroundColor: "rgba(75,192,192,1)", - pointHoverBorderColor: "rgba(220,220,220,1)", - pointHoverBorderWidth: 2, - pointRadius: 1, - pointHitRadius: 10, - data: [65, 59, 80, 81, 56, 55, 40], - spanGaps: false, - } - ] -}; -``` - -The line chart usually requires an array of labels. This labels are shown on the X axis. There must be one label for each data point. More labels than datapoints are allowed, in which case the line ends at the last data point. -The data for line charts is broken up into an array of datasets. Each dataset has a colour for the fill, a colour for the line and colours for the points and strokes of the points. These colours are strings just like CSS. You can use RGBA, RGB, HEX or HSL notation. - -The label key on each dataset is optional, and can be used when generating a scale for the chart. - -When `spanGaps` is set to true, the gaps between points in sparse datasets are filled in. By default, it is off. - -### Data Points - -The data passed to the chart can be passed in two formats. The most common method is to pass the data array as an array of numbers. In this case, the `data.labels` array must be specified and must contain a label for each point or, in the case of labels to be displayed over multiple lines an array of labels (one for each line) i.e `[["June","2015"], "July"]`. - -The alternate is used for sparse datasets. Data is specified using an object containing `x` and `y` properties. This is used for scatter charts as documented below. - -### Scatter Line Charts - -Scatter line charts can be created by changing the X axis to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties. The example below creates a scatter chart with 3 points. - -```javascript -var scatterChart = new Chart(ctx, { - type: 'line', - data: { - datasets: [{ - label: 'Scatter Dataset', - data: [{ - x: -10, - y: 0 - }, { - x: 0, - y: 10 - }, { - x: 10, - y: 5 - }] - }] - }, - options: { - scales: { - xAxes: [{ - type: 'linear', - position: 'bottom' - }] - } - } -}); -``` - -### Chart Options - -These are the customisation options specific to Line charts. These options are merged with the [global chart configuration options](#chart-configuration-global-configuration), and form the options of the chart. - -Name | Type | Default | Description ---- | --- | --- | --- -showLines | Boolean | true | If false, the lines between points are not drawn -spanGaps | Boolean | false | If true, NaN data does not break the line - -You can override these for your `Chart` instance by passing a member `options` into the `Line` method. - -For example, we could have a line chart display without an X axis by doing the following. The config merge is smart enough to handle arrays so that you do not need to specify all axis settings to change one thing. - -```javascript -new Chart(ctx, { - type: 'line', - data: data, - options: { - scales: { - xAxes: [{ - display: false - }] - } - } -}); -``` - -We can also change these defaults values for each Line type that is created, this object is available at `Chart.defaults.line`. - -### Stacked Charts - -Stacked area charts can be created by setting the Y axis to a stacked configuration. The following example would have stacked lines. - -```javascript -var stackedLine = new Chart(ctx, { - type: 'line', - data: data, - options: { - scales: { - yAxes: [{ - stacked: true - }] - } - } -}); -``` \ No newline at end of file
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
docs/04-Bar-Chart.md
@@ -1,176 +0,0 @@ ---- -title: Bar Chart -anchor: bar-chart ---- - -### Introduction -A bar chart is a way of showing data as bars. - -It is sometimes used to show trend data, and the comparison of multiple data sets side by side. - -<div class="canvas-holder"> - <canvas width="250" height="125"></canvas> -</div> - -### Example Usage -```javascript -var myBarChart = new Chart(ctx, { - type: 'bar', - data: data, - options: options -}); -``` - -Or if you want horizontal bars. - -```javascript -var myBarChart = new Chart(ctx, { - type: 'horizontalBar', - data: data, - options: options -}); -``` - -### Dataset Structure -The following options can be included in a bar chart dataset to configure options for that specific dataset. - -Some properties can be specified as an array. If these are set to an array value, the first value applies to the first bar, the second value to the second bar, and so on. - -Property | Type | Usage ---- | --- | --- -data | `Array<Number>` | The data to plot as bars -label | `String` | The label for the dataset which appears in the legend and tooltips -xAxisID | `String` | The ID of the x axis to plot this dataset on -yAxisID | `String` | The ID of the y axis to plot this dataset on -backgroundColor | `Color or Array<Color>` | The fill color of the bars. See [Colors](#chart-configuration-colors) -borderColor | `Color or Array<Color>` | Bar border color -borderWidth | `Number or Array<Number>` | Border width of bar in pixels -borderSkipped | `String or Array<String>` | Which edge to skip drawing the border for. Options are 'bottom', 'left', 'top', and 'right' -hoverBackgroundColor | `Color or Array<Color>` | Bar background color when hovered -hoverBorderColor | `Color or Array<Color>` | Bar border color when hovered -hoverBorderWidth | `Number or Array<Number>` | Border width of bar when hovered -stack | `String` | The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack) - -An example data object using these attributes is shown below. - -```javascript -var data = { - labels: ["January", "February", "March", "April", "May", "June", "July"], - datasets: [ - { - label: "My First dataset", - backgroundColor: [ - 'rgba(255, 99, 132, 0.2)', - 'rgba(54, 162, 235, 0.2)', - 'rgba(255, 206, 86, 0.2)', - 'rgba(75, 192, 192, 0.2)', - 'rgba(153, 102, 255, 0.2)', - 'rgba(255, 159, 64, 0.2)' - ], - borderColor: [ - 'rgba(255,99,132,1)', - 'rgba(54, 162, 235, 1)', - 'rgba(255, 206, 86, 1)', - 'rgba(75, 192, 192, 1)', - 'rgba(153, 102, 255, 1)', - 'rgba(255, 159, 64, 1)' - ], - borderWidth: 1, - data: [65, 59, 80, 81, 56, 55, 40], - } - ] -}; -``` -The bar chart has the a very similar data structure to the line chart, and has an array of datasets, each with colours and an array of data. -We have an array of labels too for display. In the example, we are showing the same data as the previous line chart example. - -### Chart Options - -These are the customisation options specific to Bar charts. These options are merged with the [global chart configuration options](#global-chart-configuration), and form the options of the chart. - -The default options for bar chart are defined in `Chart.defaults.bar`. - -Name | Type | Default | Description ---- |:---:| --- | --- -*hover*.mode | String | "label" | Label's hover mode. "label" is used since the x axis displays data by the index in the dataset. -scales | Object | - | - -*scales*.xAxes | Array | | The bar chart officially supports only 1 x-axis but uses an array to keep the API consistent. Use a scatter chart if you need multiple x axes. -*Options for xAxes* | | | -type | String | "Category" | As defined in [Scales](#scales-category-scale). -display | Boolean | true | If true, show the scale. -id | String | "x-axis-0" | Id of the axis so that data can bind to it -stacked | Boolean | false | If true, bars are stacked on the x-axis -barThickness | Number | | Manually set width of each bar in pixels. If not set, the bars are sized automatically. -maxBarThickness | Number | | Set this to ensure that the automatically sized bars are not sized thicker than this. Only works if barThickness is not set (automatic sizing is enabled). -categoryPercentage | Number | 0.8 | Percent (0-1) of the available width (the space between the gridlines for small datasets) for each data-point to use for the bars. [Read More](#bar-chart-barpercentage-vs-categorypercentage) -barPercentage | Number | 0.9 | Percent (0-1) of the available width each bar should be within the category percentage. 1.0 will take the whole category width and put the bars right next to each other. [Read More](#bar-chart-barpercentage-vs-categorypercentage) -gridLines | Object | [See Scales](#scales) | -*gridLines*.offsetGridLines | Boolean | true | If true, the bars for a particular data point fall between the grid lines. If false, the grid line will go right down the middle of the bars. -| | | -*scales*.yAxes | Array | `[{ type: "linear" }]` | -*Options for yAxes* | | | -type | String | "linear" | As defined in [Scales](#scales-linear-scale). -display | Boolean | true | If true, show the scale. -id | String | "y-axis-0" | Id of the axis so that data can bind to it. -stacked | Boolean | false | If true, bars are stacked on the y-axis -barThickness | Number | | Manually set height of each bar in pixels. If not set, the bars are sized automatically. -maxBarThickness | Number | | Set this to ensure that the automatically sized bars are not sized thicker than this. Only works if barThickness is not set (automatic sizing is enabled). - -You can override these for your `Chart` instance by passing a second argument into the `Bar` method as an object with the keys you want to override. - -For example, we could have a bar chart without a stroke on each bar by doing the following: - -```javascript -new Chart(ctx, { - type: "bar", - data: data, - options: { - scales: { - xAxes: [{ - stacked: true - }], - yAxes: [{ - stacked: true - }] - } - } -}); -// This will create a chart with all of the default options, merged from the global config, -// and the Bar chart defaults but this particular instance will have `stacked` set to true -// for both x and y axes. -``` - -We can also change these defaults values for each Bar type that is created, this object is available at `Chart.defaults.bar`. For horizontal bars, this object is available at `Chart.defaults.horizontalBar`. - -The default options for horizontal bar charts are defined in `Chart.defaults.horizontalBar` and are same as those of the bar chart, but with `xAxes` and `yAxes` swapped and the following additional options. - -Name | Type | Default | Description ---- |:---:| --- | --- -*Options for xAxes* | | | -position | String | "bottom" | -*Options for yAxes* | | | -position | String | "left" | - -### barPercentage vs categoryPercentage - -The following shows the relationship between the bar percentage option and the category percentage option. - -```text -// categoryPercentage: 1.0 -// barPercentage: 1.0 -Bar: | 1.0 | 1.0 | -Category: | 1.0 | -Sample: |===========| - -// categoryPercentage: 1.0 -// barPercentage: 0.5 -Bar: |.5| |.5| -Category: | 1.0 | -Sample: |==============| - -// categoryPercentage: 0.5 -// barPercentage: 1.0 -Bar: |1.||1.| -Category: | .5 | -Sample: |==============| -```
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
docs/05-Radar-Chart.md
@@ -1,125 +0,0 @@ ---- -title: Radar Chart -anchor: radar-chart ---- - -### Introduction -A radar chart is a way of showing multiple data points and the variation between them. - -They are often useful for comparing the points of two or more different data sets. - -<div class="canvas-holder"> - <canvas width="250" height="125"></canvas> -</div> - -### Example Usage - -```javascript -var myRadarChart = new Chart(ctx, { - type: 'radar', - data: data, - options: options -}); -``` - -### Dataset Structure - -The following options can be included in a radar chart dataset to configure options for that specific dataset. - -All point* properties can be specified as an array. If these are set to an array value, the first value applies to the first point, the second value to the second point, and so on. - -Property | Type | Usage ---- | --- | --- -data | `Array<Number>` | The data to plot in a line -label | `String` | The label for the dataset which appears in the legend and tooltips -fill | `Boolean` | If true, fill the area under the line -lineTension | `Number` | Bezier curve tension of the line. Set to 0 to draw straightlines. *Note* This was renamed from 'tension' but the old name still works. -backgroundColor | `Color` | The fill color under the line. See [Colors](#chart-configuration-colors) -borderWidth | `Number` | The width of the line in pixels -borderColor | `Color` | The color of the line. -borderCapStyle | `String` | Cap style of the line. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap) -borderDash | `Array<Number>` | Length and spacing of dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash) -borderDashOffset | `Number` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset) -borderJoinStyle | `String` | Line joint style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin) -pointBorderColor | `Color or Array<Color>` | The border color for points. -pointBackgroundColor | `Color or Array<Color>` | The fill color for points -pointBorderWidth | `Number or Array<Number>` | The width of the point border in pixels -pointRadius | `Number or Array<Number>` | The radius of the point shape. If set to 0, nothing is rendered. -pointHoverRadius | `Number or Array<Number>` | The radius of the point when hovered -pointHitRadius | `Number or Array<Number>` | The pixel size of the non-displayed point that reacts to mouse events -pointHoverBackgroundColor | `Color or Array<Color>` | Point background color when hovered -pointHoverBorderColor | `Color or Array<Color>` | Point border color when hovered -pointHoverBorderWidth | `Number or Array<Number>` | Border width of point when hovered -pointStyle | `String or Array<String>` | The style of point. Options include 'circle', 'triangle', 'rect', 'rectRounded', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash' - -An example data object using these attributes is shown below. - -```javascript -var data = { - labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"], - datasets: [ - { - label: "My First dataset", - backgroundColor: "rgba(179,181,198,0.2)", - borderColor: "rgba(179,181,198,1)", - pointBackgroundColor: "rgba(179,181,198,1)", - pointBorderColor: "#fff", - pointHoverBackgroundColor: "#fff", - pointHoverBorderColor: "rgba(179,181,198,1)", - data: [65, 59, 90, 81, 56, 55, 40] - }, - { - label: "My Second dataset", - backgroundColor: "rgba(255,99,132,0.2)", - borderColor: "rgba(255,99,132,1)", - pointBackgroundColor: "rgba(255,99,132,1)", - pointBorderColor: "#fff", - pointHoverBackgroundColor: "#fff", - pointHoverBorderColor: "rgba(255,99,132,1)", - data: [28, 48, 40, 19, 96, 27, 100] - } - ] -}; -``` -For a radar chart, to provide context of what each point means, we include an array of strings that show around each point in the chart. -For the radar chart data, we have an array of datasets. Each of these is an object, with a fill colour, a stroke colour, a colour for the fill of each point, and a colour for the stroke of each point. We also have an array of data values. -The label key on each dataset is optional, and can be used when generating a scale for the chart. - - -### Chart Options - -These are the customisation options specific to Radar charts. These options are merged with the [global chart configuration options](#global-chart-configuration), and form the options of the chart. - -The default options for radar chart are defined in `Chart.defaults.radar`. - -Name | Type | Default | Description ---- | --- | --- | --- -scale | Object | [See Scales](#scales) and [Defaults for Radial Linear Scale](#scales-radial-linear-scale) | Options for the one scale used on the chart. Use this to style the ticks, labels, and grid lines. -*scale*.type | String |"radialLinear" | As defined in ["Radial Linear"](#scales-radial-linear-scale). -*elements*.line | Object | | Options for all line elements used on the chart, as defined in the global elements, duplicated here to show Radar chart specific defaults. -*elements.line*.lineTension | Number | 0 | Tension exhibited by lines when calculating splineCurve. Setting to 0 creates straight lines. -startAngle | Number | 0 | The number of degrees to rotate the chart clockwise. - -You can override these for your `Chart` instance by passing a second argument into the `Radar` method as an object with the keys you want to override. - -For example, we could have a radar chart without a point for each on piece of data by doing the following: - -```javascript -new Chart(ctx, { - type: "radar", - data: data, - options: { - scale: { - reverse: true, - ticks: { - beginAtZero: true - } - } - } -}); -// This will create a chart with all of the default options, merged from the global config, -// and the Radar chart defaults but this particular instance's scale will be reversed as -// well as the ticks beginning at zero. -``` - -We can also change these defaults values for each Radar type that is created, this object is available at `Chart.defaults.radar`.
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
docs/06-Polar-Area-Chart.md
@@ -1,108 +0,0 @@ ---- -title: Polar Area Chart -anchor: polar-area-chart ---- -### Introduction -Polar area charts are similar to pie charts, but each segment has the same angle - the radius of the segment differs depending on the value. - -This type of chart is often useful when we want to show a comparison data similar to a pie chart, but also show a scale of values for context. - -<div class="canvas-holder"> - <canvas width="250" height="125"></canvas> -</div> - -### Example Usage - -```javascript -new Chart(ctx, { - data: data, - type: 'polarArea', - options: options -}); -``` - -### Dataset Structure - -The following options can be included in a polar area chart dataset to configure options for that specific dataset. - -Some properties are specified as arrays. The first value applies to the first bar, the second value to the second bar, and so on. - -Property | Type | Usage ---- | --- | --- -data | `Array<Number>` | The data to plot as arcs -label | `String` | The label for the dataset which appears in the legend and tooltips -backgroundColor | `Array<Color>` | The fill color of the arcs. See [Colors](#chart-configuration-colors) -borderColor | `Array<Color>` | Arc border color -borderWidth | `Array<Number>` | Border width of arcs in pixels -hoverBackgroundColor | `Array<Color>` | Arc background color when hovered -hoverBorderColor | `Array<Color>` | Arc border color when hovered -hoverBorderWidth | `Array<Number>` | Border width of arc when hovered - -An example data object using these attributes is shown below. - -```javascript -var data = { - datasets: [{ - data: [ - 11, - 16, - 7, - 3, - 14 - ], - backgroundColor: [ - "#FF6384", - "#4BC0C0", - "#FFCE56", - "#E7E9ED", - "#36A2EB" - ], - label: 'My dataset' // for legend - }], - labels: [ - "Red", - "Green", - "Yellow", - "Grey", - "Blue" - ] -}; -``` -As you can see, for the chart data you pass in an array of objects, with a value and a colour. The value attribute should be a number, while the color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL. - -### Chart Options - -These are the customisation options specific to Polar Area charts. These options are merged with the [global chart configuration options](#global-chart-configuration), and form the options of the chart. - -Name | Type | Default | Description ---- | --- | --- | --- -startAngle | Number | -0.5 * Math.PI | Sets the starting angle for the first item in a dataset -scale | Object | [See Scales](#scales) and [Defaults for Radial Linear Scale](#scales-radial-linear-scale) | Options for the one scale used on the chart. Use this to style the ticks, labels, and grid. -*scale*.type | String |"radialLinear" | As defined in ["Radial Linear"](#scales-radial-linear-scale). -*animation*.animateRotate | Boolean |true | If true, will animate the rotation of the chart. -*animation*.animateScale | Boolean | true | If true, will animate scaling the chart. -*legend*.*labels*.generateLabels | Function | `function(data) {} ` | Returns labels for each the legend -*legend*.onClick | Function | function(event, legendItem) {} ` | Handles clicking an individual legend item -legendCallback | Function | `function(chart) ` | Generates the HTML legend via calls to `generateLegend` - -You can override these for your `Chart` instance by passing a second argument into the `PolarArea` method as an object with the keys you want to override. - -For example, we could have a polar area chart with a black stroke on each segment like so: - -```javascript -new Chart(ctx, { - data: data, - type: "polarArea", - options: { - elements: { - arc: { - borderColor: "#000000" - } - } - } -}); -// This will create a chart with all of the default options, merged from the global config, -// and the PolarArea chart defaults but this particular instance will have `elements.arc.borderColor` set to `"#000000"`. -``` - -We can also change these defaults values for each PolarArea type that is created, this object is available at `Chart.defaults.polarArea`.
true
Other
chartjs
Chart.js
3e94b9431a5b3d6e4bfbfd6a2339a350999b3292.json
Update the docs structure/content to use GitBook (#3751) Update the docs structure/content to use GitBook
docs/07-Pie-Doughnut-Chart.md
@@ -1,115 +0,0 @@ ---- -title: Pie & Doughnut Charts -anchor: doughnut-pie-chart ---- -### Introduction -Pie and doughnut charts are probably the most commonly used charts there are. They are divided into segments, the arc of each segment shows the proportional value of each piece of data. - -They are excellent at showing the relational proportions between data. - -Pie and doughnut charts are effectively the same class in Chart.js, but have one different default value - their `cutoutPercentage`. This equates what percentage of the inner should be cut out. This defaults to `0` for pie charts, and `50` for doughnuts. - -They are also registered under two aliases in the `Chart` core. Other than their different default value, and different alias, they are exactly the same. - -<div class="canvas-holder half"> - <canvas width="250" height="125"></canvas> -</div> - -<div class="canvas-holder half"> - <canvas width="250" height="125"></canvas> -</div> -<br> - -### Example Usage - -```javascript -// For a pie chart -var myPieChart = new Chart(ctx,{ - type: 'pie', - data: data, - options: options -}); -``` - -```javascript -// And for a doughnut chart -var myDoughnutChart = new Chart(ctx, { - type: 'doughnut', - data: data, - options: options -}); -``` - -### Dataset Structure - -Property | Type | Usage ---- | --- | --- -data | `Array<Number>` | The data to plot as arcs -label | `String` | The label for the dataset which appears in the legend and tooltips -backgroundColor | `Array<Color>` | The fill color of the arcs. See [Colors](#chart-configuration-colors) -borderColor | `Array<Color>` | Arc border color -borderWidth | `Array<Number>` | Border width of arcs in pixels -hoverBackgroundColor | `Array<Color>` | Arc background color when hovered -hoverBorderColor | `Array<Color>` | Arc border color when hovered -hoverBorderWidth | `Array<Number>` | Border width of arc when hovered - -An example data object using these attributes is shown below. - -```javascript -var data = { - labels: [ - "Red", - "Blue", - "Yellow" - ], - datasets: [ - { - data: [300, 50, 100], - backgroundColor: [ - "#FF6384", - "#36A2EB", - "#FFCE56" - ], - hoverBackgroundColor: [ - "#FF6384", - "#36A2EB", - "#FFCE56" - ] - }] -}; -``` - -For a pie chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. You can also add an array of background colors. The color attributes should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL. - -### Chart Options - -These are the customisation options specific to Pie & Doughnut charts. These options are merged with the [global chart configuration options](#global-chart-configuration), and form the options of the chart. - -Name | Type | Default | Description ---- | --- | --- | --- -cutoutPercentage | Number | 50 - for doughnut, 0 - for pie | The percentage of the chart that is cut out of the middle. -rotation | Number | -0.5 * Math.PI | Starting angle to draw arcs from -circumference | Number | 2 * Math.PI | Sweep to allow arcs to cover -*animation*.animateRotate | Boolean |true | If true, will animate the rotation of the chart. -*animation*.animateScale | Boolean | false | If true, will animate scaling the Doughnut from the centre. -*legend*.*labels*.generateLabels | Function | `function(chart) {} ` | Returns a label for each item to be displayed on the legend. -*legend*.onClick | Function | function(event, legendItem) {} ` | Handles clicking an individual legend item - -You can override these for your `Chart` instance by passing a second argument into the `Doughnut` method as an object with the keys you want to override. - -For example, we could have a doughnut chart that animates by scaling out from the centre like so: - -```javascript -new Chart(ctx,{ - type:"doughnut", - options: { - animation:{ - animateScale:true - } - } -}); -// This will create a chart with all of the default options, merged from the global config, -// and the Doughnut chart defaults but this particular instance will have `animateScale` set to `true`. -``` - -We can also change these default values for each Doughnut type that is created, this object is available at `Chart.defaults.doughnut`. Pie charts also have a clone of these defaults available to change at `Chart.defaults.pie`, with the only difference being `cutoutPercentage` being set to 0.
true