Chart.js graph with just two cordinates - charts

I want to make a simple graph (just a line between two coordinates - (2,5) and (5,10)).
HtML
<canvas id="line" width="600" height="400"></canvas>
JavaScript
var lineData = {
type: "line",
data: {
datasets: [{
label: "Test",
data: [{
x: 2,
y: 5
}, {
x: 5,
y: 10
}],
}]
}
}
var line = document.getElementById('line').getContext('2d');
new Chart(line).Line(lineData);
Unfortunately, this doesn't show anything.

Please refer the code snippet below to render the chart correctly, or can visit the fiddle -> https://jsfiddle.net/pgv2jon3/1/
var lineData = {
type: "line",
data: {
datasets: [{
label: "Test",
data: [{
x: 2,
y: 5
}, {
x: 5,
y: 10
}],
}]
}
}
var ctx = document.getElementById('line').getContext('2d');
new Chart(ctx, lineData);

Related

Custom tooltip title based on dictionary mapping of values

MWE: See a graph below with countries in the x-axis. What is the best way to show the whole name in the tooltip instead of the acronym? (Show "Germany" instead of "GER", France instead of "FRA", etc.). I have like 10 or 15 of those.
SEE FULL CODE IN jsfiddle
var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
https://jsfiddle.net/user3507584/6zpb715x/6/
You can add an object with translations where the key is the value from the label and the value is the full country name:
var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
var translations = {
GER: 'Germany',
FRA: 'France',
LT: "Italy"
}
var barChartData2 = {
labels: labels2,
datasets: [{
label: 'Student Count',
backgroundColor: '#ccece6',
data: example2
}]
};
function drawChart(el, data, title) {
var ctx = document.getElementById(el).getContext("2d");
var bar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each bar to be 2px wide and green
elements: {
rectangle: {
borderWidth: 2,
borderColor: '#98c4f9',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'bottom',
},
title: {
display: true,
text: title
},
scales: {
yAxes: [{
ticks: {
beginAtZero: 0,
min: 0
}
}],
xAxes: [{
ticks: {
// Show all labels
autoSkip: false,
callback: function(tick) {
var characterLimit = 20;
if (tick.length >= characterLimit) {
return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';;
}
return tick;
}
}
}]
},
tooltips: {
callbacks: {
title: function(tooltipItem) {
return translations[tooltipItem[0].xLabel];
}
}
}
}
});
console.log(bar);
};
drawChart('canvas0', barChartData2, 'example title');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.js"></script>
<div id="container">
<canvas id="canvas0"></canvas>
</div>

ChartJS multichart graph not showing correctly legends

Am trying to create bar graph with multiple plots using chartjs and the graph is generated successfully but one of the legend is not showing correctly.
Am using Chartjs 2.9.3 version.
One of the bar legendary is showing as circle instead of rectangle box. Kindly let me know if any workaround to get the correct legendary.
Bar graph show circle in the legendary
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [
{
label: 'Label1',
data: [3,4],
type: 'scatter',
backgroundColor: 'red',
pointStyle:'circle',
pointRadius:5
},
{
label: 'Label2',
data: [1,2],
type: 'scatter',
backgroundColor: 'blue',
pointStyle:'triangle',
pointRadius:5
},
{
backgroundColor: 'grey',
label: 'Label3',
data: [1,2],
borderWidth: 1,
type: 'bar'
}
]
},
options: {
responsive:false,
legend: {
labels : {
usePointStyle: true
}
},
title: {
display: true
},
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: '$/MWh'
}
}]
}
}
});
If the usePointstyle flag is set in the legend it defaults to the circle. In V2 this is not configurable for bar charts so you have 2 options
You can switch to a html legend and style that. Or you can update to chart.js version 3 where you can configure it for bar charts:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'yellow'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'pink',
pointStyle: 'rect'
}
]
},
options: {
plugins: {
legend: {
labels: {
usePointStyle: true
}
}
}
}
}
var 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.5.0/chart.js"></script>
</body>

How to add annotation to Google Bar Chart where dataset comes from Google Sheet [duplicate]

I need to put labels over my google.chart.Bar (not google.visualization.BarChart) the chart is correctly visualized but only shows values on mouse over the bars,please helpme!.
without mouse over
with mouse over
the data is taked from hidden inputs... here the code :
var data3 = new google.visualization.arrayToDataTable([
['Ambitos', 'Programados', 'Terminados',{ role: 'style' }],
['ex', parseInt(document.getElementById("sumex").value),(parseInt(document.getElementById("sumex").value))-( parseInt(document.getElementById("sumpex").value)),document.getElementById("sumex").value],
['ma', parseInt(document.getElementById("summa").value),(parseInt(document.getElementById("summa").value))-( parseInt(document.getElementById("sumpma").value)),document.getElementById("summa").value],
['mo', parseInt(document.getElementById("summo").value),(parseInt(document.getElementById("summo").value))-( parseInt(document.getElementById("sumpmo").value)),document.getElementById("summo").value],
['re', parseInt(document.getElementById("sumre").value),(parseInt(document.getElementById("sumre").value))-( parseInt(document.getElementById("sumpre").value)),document.getElementById("sumre").value],
['tx', parseInt(document.getElementById("sumtx").value),(parseInt(document.getElementById("sumtx").value))-( parseInt(document.getElementById("sumptx").value)),document.getElementById("sumtx").value]]);
var view3 = new google.visualization.DataView(data3);
view3.setColumns([0,1,2,
{ calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation" },3]);
var options3 = {
legend: { position: "none" },
chart: {
title: 'Resumen General',
subtitle: 'programados v/s terminados'},
series: {},
axes: { y: {
distance: {label: ''}, } },
chartArea : { width:"95%", height:"80%"} };
var chart3 = new google.charts.Bar(document.getElementById('barras'));
chart3.draw(data3, options3);
p.d. sorry for my bad english!
unfortunately, annotations (bar labels) are not supported on Material charts
recommend using Core chart, with the following option instead...
theme: 'material'
an separate annotation column should be added for each series column,
that should have annotations
when using a DataView to add annotation columns,
be sure to draw the chart using the view (view3),
instead of the original data table (data3)
see following working snippet...
google.charts.load('current', {
callback: function () {
var data3 = new google.visualization.arrayToDataTable([
['Ambitos', 'Programados', 'Terminados',{ role: 'style' }],
['ex', 8,(8)-(6),''],
['ma', 6,(6)-(4),''],
['mo', 4,(4)-(2),''],
['re', 2,(2)-(1),''],
['tx', 1,(1)-(0),'']]);
var view3 = new google.visualization.DataView(data3);
view3.setColumns([0,
1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2,
{
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
},
3
]);
var options3 = {
legend: { position: "none" },
chart: {
title: 'Resumen General',
subtitle: 'programados v/s terminados'
},
series: {},
axes: {
y: {
distance: {label: ''},
}
},
chartArea : {
width:"95%",
height:"80%"
},
theme: 'material'
};
var chart3 = new google.visualization.ColumnChart(document.getElementById('barras'));
chart3.draw(view3, options3);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barras"></div>
note: list of options unavailable to Material --> Tracking Issue for Material Chart Feature Parity

Offset tick labels to center between ticks on horizontal bar chart

I am creating a horizontal bar chart using Google charts and I want to position the horizontal axis tick labels between ticks (offset tick label to the right by half a tick). There is also no guarantee that each label will be the same number of characters. Is there any functionality to achieve this?
This is my function for creating the chart
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Performance", "Level", { role: "style" }],
["PL", 1.01, "#5aa66d"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: function (dt, rowIndex) { return 'PL=' + (dt.getValue(rowIndex, 1)).toString()} ,
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var options = {
width: 600,
height: 100,
bar: { groupWidth: "80%" },
legend: { position: "none" },
hAxis: {
minValue: 0,
maxValue: 3,
ticks: [
{ v: 0, f: 'Col1' },
{ v: 1, f: 'Col2' },
{ v: 2, f: 'Col3' },
{ v: 3, f: 'Col4' }
]
}
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(view, options);
}
This is the chart currently
https://imgur.com/LvQEbtY
and this is what I want to achieve:
https://imgur.com/hwvIOG2
EDIT:
For ideas, right before chart.draw I add an event listener and find all the text tags and modify the 'x' attribute to re-position the tick labels. This works, but it also affects the on-bar data label which is a problem.
google.visualization.events.addListener(chart, 'ready', function () {
var elements = document.getElementById("barchart_values").getElementsByTagName("text");
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute('x', (Number(elements[i].getAttribute('x')) + (chart.getChartLayoutInterface().getBoundingBox('chartarea').width / 4 / 2))); //chart width / tick count / 2
}
});
first, we won't be able to offset the grid lines and use the ticks option.
let's offset the grid lines by making the major transparent and the minor visible.
we can also offset the baseline by setting to a negative value.
baseline: -0.5,
minorGridlines: {
color: '#cccccc',
count: 1
},
gridlines: {
color: 'transparent',
count: 4
},
then, in order to have custom tick labels, we can use your original idea to change them manually.
just need a unique attribute to separate them from the bar labels.
here, the text-anchor attribute is used.
if (elements[i].getAttribute('text-anchor') === 'middle') {
elements[i].textContent = 'Col' + parseInt(elements[i].textContent) + 1;
}
see following working snippet...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
["Performance", "Level", { role: "style" }],
["PL", 1.01, "#5aa66d"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, rowIndex) { return 'PL=' + (dt.getValue(rowIndex, 1)).toString()} ,
sourceColumn: 1,
type: "string",
role: "annotation"
}, 2]);
var options = {
width: 600,
height: 100,
bar: { groupWidth: "80%" },
legend: { position: "none" },
hAxis: {
baseline: -0.5,
minorGridlines: {
color: '#cccccc',
count: 1
},
gridlines: {
color: 'transparent',
count: 4
},
minValue: 0,
maxValue: 3,
}
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
google.visualization.events.addListener(chart, 'ready', function () {
var elements = document.getElementById("barchart_values").getElementsByTagName("text");
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute('text-anchor') === 'middle') {
elements[i].textContent = 'Col' + (parseInt(elements[i].textContent) + 1);
}
}
});
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barchart_values"></div>
the above will ensure all the labels remain visible, just simply moving them, could cause them to be pushed off the visible portion of the chart.

Canvasjs doughnut chart, remove labels

I am using canvasjs to create a doughnut chart - the chart itself works great but I want the labels to be removed from the chart itself and only be shown in the tooltip.
I have tried the below based on what I read on the canvasjs site but it does not hide the label:
<div id="chartContainer" style="width:150px; height:150px;"></div>
var chart = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
theme: "theme2",
creditText:"",
axisY:{
valueFormatString: " ",
tickLength: 0
},
axisX:{
valueFormatString: " ",
tickLength: 0
},
data: [
{
type: "doughnut",
startAngle:270 ,
toolTipContent: "{label}: {y}",
dataPoints: [
{ y: 2, label: "L1"},
{ y: 3, label: "L2"},
{ y: 8, label: "L3"}
]
}
]
});
chart.render();
Is there a way to stop the label showing in the chart itself but still have a label value to use for the tooltip?
https://jsfiddle.net/befmrhz4/
Just found a way to do it using the name attribute in dataPoints:
var chart = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
theme: "theme2",
data: [
{
type: "doughnut",
startAngle:270 ,
toolTipContent: "{name}: {y}",
dataPoints: [
{ y: 2, name: "L1"},
{ y: 3, name: "L2"},
{ y: 8, name: "L3"}
]
}
]
});
chart.render();
http://canvasjs.com/docs/charts/chart-options/data/datapoints/