Where do i add the begin at zero (chart.js) - javascript

I've made two charts, one line chart and one bar-chart, that you can switch between and the charts contains different data. The problem is that I can't seem to make them begin at zero? Where in the script do I put the code so both charts begin at zero, because now it just doesn't work or the whole bar just disappears.
<script>
let lineConfig = {
type: 'line',
data: {
labels: ["2012", "2013", "2014", "2015", "2016", "2017"],
datasets: [{
label: "Miljoner ton",
data: [56.38, 59.3, 61.81, 58.83, 52.32, 66.86],
lineTension: 0.1,
backgroundColor: "rgba(0,255,0,0.4)",
borderColor: "green", // The main line color
borderCapStyle: 'square',
pointBorderColor: "white",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "green",
pointHoverBorderWidth: 2,
pointRadius: 4,
}]
}
},
barConfig = {
type: 'bar',
data: {
labels: ['Palmolja', "Sojaolja", 'Animaliskt fett', 'Solrosolja', 'Rapsolja', 'Annat'],
datasets: [{
label: "Procent",
data: [28.6, 25.3, 13.2, 8.0, 12.2, 9.6],
backgroundColor: "rgba(0,255,0,0.4)",
borderColor: "green", // The main line color
borderCapStyle: 'square',
pointBorderColor: "white",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "green",
pointHoverBorderWidth: 2,
pointRadius: 4,
}]
}
},
activeType = 'bar', // we'll start with a bar chart.
myChart;
function init(config) {
// create a new chart with the supplied config.
myChart = new Chart(document.getElementById('chart'), config);
}
// first init as a bar chart.
init(barConfig);
document.getElementById('switch').addEventListener('click', function(e) {
// every time the button is clicked we destroy the existing chart.
myChart.destroy();
if (activeType == 'bar') {
// chart was a bar, init a new line chart.
activeType = 'line';
init(lineConfig);
return;
}
// chart was a line, init a new bar chart.
activeType = 'bar';
init(barConfig);
});
</script>

Assuming you mean for your linear y-axis then the documentation specifies the following:
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
Edit as per OP comment:
The options property is a sibling of type and data, e.g.:
{
type: 'line',
data: {
labels: [...],
datasets: [{
data: [...]
}]
},
options: {
...
}
}

Related

how change color of labels of legends of chart.js

i use of chart.js package for create a chart.
my problem:
how change the color of label of each legends?
for example:
color of "legend1" be: red.
color of "legend2" be: blue.
my codes:
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
data: {
labels: ['۱۴۰۰/۰۱/۰۱', '۱۴۰۰/۰۱/۰۲', '۱۴۰۰/۰۱/۰۳', '۱۴۰۰/۰۱/۰۴', '۱۴۰۰/۰۱/۰۵', '۱۴۰۰/۰۱/۰۶'],
datasets: [{
type: 'line',
label: 'legend1',
backgroundColor: 'rgb(14, 156, 255)',
data: [6, 5.5, 4, 7, 5.4, 5.8],
fill: false,
borderColor: 'rgb(14, 156, 255)',
tension: 0
},
{
type: 'line',
label: 'legend2',
backgroundColor: 'rgb(22, 185, 156)',
data: [6.2, 5.7, 3.8, 7.2, 5.2, 5.9],
fill: false,
borderColor: 'rgb(22, 185, 156)',
tension: 0
}
] //end : datasets
}, // end: data
options: {
plugins: {
legend: {
labels: {
font: {
size: 18
} // end: font
} // end: labels
,
position: 'bottom',
rtl: true,
align: "start"
} // end: legend
}, // end: plugins
scales: {
y: {
beginAtZero: true,
display: false
} // end: y
,
x: {
grid: {
borderDash: [6, 5],
lineWidth: 1,
color: '#CCCCCC'
} // end: grid
} //end:x
} // end: scales
} //end: options
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.7.1/dist/chart.min.js"></script>
<canvas id="myChart" width="778" height="433"></canvas>
my problem is just that: how change the color of each legend's text?
color of "legend1" text and color of "legend2" text.
my codes result:
To achieve what you want you will need to use a custom generateLabels function like so:
const legendColors = ['red', 'blue']
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
plugins: {
legend: {
labels: {
generateLabels: (chart) => {
const datasets = chart.data.datasets;
const {
labels: {
usePointStyle,
pointStyle,
textAlign,
color
}
} = chart.legend.options;
return chart._getSortedDatasetMetas().map((meta, i) => {
const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
const borderWidth = Chart.helpers.toPadding(style.borderWidth);
return {
text: datasets[meta.index].label,
fillStyle: style.backgroundColor,
fontColor: legendColors[i],
hidden: !meta.visible,
lineCap: style.borderCapStyle,
lineDash: style.borderDash,
lineDashOffset: style.borderDashOffset,
lineJoin: style.borderJoinStyle,
lineWidth: (borderWidth.width + borderWidth.height) / 4,
strokeStyle: style.borderColor,
pointStyle: pointStyle || style.pointStyle,
rotation: style.rotation,
textAlign: textAlign || style.textAlign,
borderRadius: 0, // TODO: v4, default to style.borderRadius
// Below is extra data used for toggling the datasets
datasetIndex: meta.index
};
}, this);
}
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>
Did you try the hex format ?
For example, you could try replacing "rgb(14, 156, 255)" by "#0e9cff"
More info here : https://devsheet.com/code-snippet/change-color-of-the-line-in-chartjs-line-chart/

Chart.js Bars overlapping

I tried tweaking, adding, subtracting from the chart.js bar code yet I get overlapping bars as you can see:
Code:
fetch("/Ajax").then(response => response.json()).then(function (response) {
if (response == null) {
console.log(response);
} else {
console.log(response);
const config = {
type: 'bar',
data: {
labels: chart_labels,
datasets: [{
label: "My First dataset",
fill: true,
backgroundColor: gradientStroke,
borderColor: '#d346b1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: response
}]
},
options: gradientChartOptionsConfigurationWithTooltipPurple
};
var dtx = document.getElementById("chartBig1").getContext("2d");
var myChartData = new Chart(dtx, config);
$("#0").click(function() {
var data = response;
data.datasets[0].data = response;
data.labels = response;//['9','10','11','12','1','2','3','4','5','6','7','8','9','10','11','12'];
myChartData.update();
});
I'm not sure how I can make the bars separated from each other.

Chart.js changing the color of the max value bar

I'm new to JS, I want to create a bar chart where the column with the max value has a different color compared to the others. I can create the chart but I don't manage to access the single column properties. I have been looking for answers on the web but none of the solutions I have found so far helped me. The workflow is the following:
I ask the user for a text input,
Once the user press a button the script calls a function in python (I use python flask) that returns me an array of values and labels,
Then a chart appears on the webpage with these values and labels.
Everything works fine, I'm just not able to change the color of a single bar.
Here is the JS:
$(function() {
$('a#process_input').bind('click', function() {
$.getJSON('/background_process', {
smile: $('input[name="text_string"]').val(),
}, function(data) {
$("#result").text(data.output);
var labels = data.labels;
var values = data.values;
Chart.defaults.global.responsive = false;
var chartData = {
labels : labels,
datasets : [{
label: 'data_label',
fill: true,
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 : values,
scaleShowLabels: true,
spanGaps: false
}]
}
// get chart canvas
var ctx = document.getElementById("myCanvas").getContext("2d");
// create the chart using the chart canvas
var myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scaleShowValues: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
autoSkip: false
}
}]
}
}
});
});
});
});
Here is an example of what I mean:
I think the easiest way to do it is by defining backgroundColor for each bars. Then you can find the max index and change the color. Here is a simplified example:
function argMax(array) {
return array.map((x, i) => [x, i]).reduce((r, a) => (a[0] > r[0] ? a : r))[1];
}
// dummy data
var data = [12, 19, 1, 14, 3, 10, 9];
var labels = data.map((x, i) => i.toString());
// other data color
var color = data.map(x => 'rgba(75,192,192,0.4)');
// change max color
color[argMax(data)] = 'red';
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'value',
data: data,
backgroundColor: color,
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0-beta/Chart.js"></script>
<canvas id="myChart" width="600" height="300"></canvas>
backgroundColor: "rgba(75,192,192,0.4)"
instead of giving it a single color, you can add an array:
backgroundColor:["rgba(255, 99, 132, 0.2)","rgba(255, 159, 64, 0.2)","rgba(255, 205, 86, 0.2)"]
Example:
new Chart(document.getElementById("chartjs-1"), {
"type": "bar",
"data": {
"labels": ["First", "Second", "Third", "Fourth"],
"datasets": [{
"label": "Example Dataset",
"data": [65, 59, 80, 31],
"fill": false,
"backgroundColor": ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 99, 132, 0.2)"],
"borderColor": ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 99, 132)", "rgb(255, 99, 132)"],
"borderWidth": 1
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chartjs-1" class="chartjs">https://stackoverflow.com/posts/51843404/edit#
In the documentation [] denotes which properties accept also arrays (backgroundColor - Color/Color[])

How to hide tooltips with their respective dataset

I'm using charts.js. For my current need, I managed to find a way to configure tooltips to be always visible regardless of the hover event. My problem is that the tooltip visibility does not follow the dataset behaviour. On charts.js, you can click on a dataset in order to remove it from the graph. My graph does that, but the tooltips are still there visible, floating within the graph with no dataset to represent. Is there a way to hide then with the dataset data when the label is clicked ?
Here is an example of the current state of what i said. https://jsfiddle.net/CaioSantAnna/ddejheg0/ .
HTML
<canvas id="linha"></canvas>
Javascript
Chart.plugins.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
ctx = document.getElementById("linha");
var linha = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: true,
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,
responsive: true,
animation: true,
},
{
label: "Second dataset",
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(0,0,0,0.4)",
borderColor: "rgba(0,0,0,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(0,0,0,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(0,0,0,1)",
pointHoverBorderColor: "rgba(0,0,0,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [13, 78, 60, 75, 90, 10, 27],
spanGaps: false,
responsive: true,
animation: true,
}
]
},
options: {
tooltips: {
callbacks: {
title: function (tooltipItem, data) { return "" },
label: function (tooltipItem, data) {
var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || 'Other';
var label = data.labels[tooltipItem.index];
return value;
}
}
},showAllTooltips: true
}
});
To reproduce the problem, just click in one of the labels on the top of the graph.
Thanks in advance.
Just to close the question, I ended up changing to amcharts(https://www.amcharts.com/). It has features like the one i was trying to achieve with chart.js and is free to use under a linkware license.
Thanks again.

Chart JS Line insert Picture

Simple Setup:
I have a RoR Application and a ChartJS Line Diagramm.
I want to add a Picture at a specific place but also text.
In the progress of the RoR Application answers of users will show up after time. Later the answer of two people will be shown, who is closer to the Average.
In my case I only need to know how a Picture could rendered inside.
Picture What it should look like
Here is my actual Code:
var points = [];
var data = {
datasets: [{
label: 'Antworten',
data: points,
radius: 6,
borderColor: "#000000",
borderWidth: 2,
backgroundColor: "#FF0000"
},
{
label: "",
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,0,1)",
borderColor: "rgba(0,0,0,1)",
borderCapStyle: 'butt',
borderDash: [0],
borderDashOffset: 0.0,
showLine: true,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(0,0,0,1)",
pointBackgroundColor: "rgba(1,0,0,1)",
pointBorderWidth: 8,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(0,0,0,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointStyle: "circle",
pointHitRadius: 10,
data: [{
x: 0,
y: 0
},{
x: 100,
y: 0
}],
borderColor: "#000000",
borderWidth: 5,
backgroundColor: "#FF0000"
}
]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, {
type: 'line',
data,
options: {
legend: {
display: false
},
showLines: false,
scales: {
xAxes: [{
type: 'linear',
gridLines: {
display: false
},
position: 'bottom',
ticks: {
max: 100,
min: 0,
stepSize: 10
}
}],
yAxes: [{
display: false,
ticks: {
max: 1,
min: 0,
stepSize: 1
}
}]
}
}
});
};
Found an Answer:
Here my solution
var user_a = new Image();
user_a.src = 'http://i.imgur.com/fwhrCBs.png';
var data = {
datasets: [
{
label: 'Spieler 1',
data: user_a_answer,
radius: 1,
borderColor: "#000000",
borderWidth: 2,
pointStyle: user_a,
}]

Categories