ChartJS legend is not included in image if is a custom legend - javascript

As the title says the custom legend of a ChartJS is not included in the image that i am saving from the canvas and that is probably also the problem, because the legend is not part of the canvas anymore is not included in the image. Is there any way to include the custom legend in the canvas?
https://codepen.io/anon/pen/XZGyNW
var myChart = new Chart(document.getElementById('mychart'), {
type: 'pie',
animation:{
animateScale:true
},
data: {
labels: visitData,
datasets: [{
label: 'Visitor',
data: visitorData,
backgroundColor: [
"#a2d6c4",
"#36A2EB",
"#3e8787",
"#579aac",
"#7dcfe8",
"#b3dfe7",
]
}]
},
options: {
responsive: true,
legend: false,
legendCallback: function(chart) {
var legendHtml = [];
legendHtml.push('<ul>');
var item = chart.data.datasets[0];
for (var i=0; i < item.data.length; i++) {
legendHtml.push('<li>');
legendHtml.push('<span class="chart-legend" style="background-color:' + item.backgroundColor[i] +'"></span>');
legendHtml.push('<span class="chart-legend-label-text">' + item.data[i] + ' person - '+chart.data.labels[i]+' times</span>');
legendHtml.push('</li>');
}
legendHtml.push('</ul>');
legendHtml.push('<table border="1" width="600"><tr><th>Company</th><th>Contact</th><th>Country</th></tr><tr><td>Alfreds Futterkiste</td><td>Maria Anders</td><td>Germany</td></tr><tr><td>Centro comercial Moctezuma</td><td>Francisco Chang</td><td>Mexico</td></tr><tr><td>Ernst Handel</td><td>Roland Mendel</td><td>Austria</td></tr><tr><td>Island Trading</td><td>Helen Bennett</td><td>UK</td></tr><tr><td>Laughing Bacchus Winecellars</td><td>Yoshi Tannamuri</td><td>Canada</td></tr><tr><td>Magazzini Alimentari Riuniti</td><td>Giovanni Rovelli</td><td>Italy</td></tr></table>');
return legendHtml.join("");
},
tooltips: {
enabled: true,
mode: 'label',
callbacks: {
label: function(tooltipItem, data) {
var indice = tooltipItem.index;
return data.datasets[0].data[indice] + " person visited " + data.labels[indice] + ' times';
}
}
},
}
});
$('#my-legend-con').html(myChart.generateLegend());

Related

echart data point gradient color

I am trying to make a gradient line chart, The issue is with tooltip legend color and color of data points, they appear in brown gradient which was the default.
I was able to change the tooltip color, anyhow that is not the actual data point color but able to fix it to one color at least. whereas the points on the line do not pick up the color of the line.
Can someone point me in right direction?
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
var option;
var data = [["2020-06-05",116],["2020-06-06",129],["2020-06-07",135],["2020-06-08",86],["2020-06-09",73],["2020-06-10",85],["2020-06-11",73],["2020-06-12",68],["2020-06-13",92],["2020-06-14",130],["2020-06-15",245],["2020-06-16",139],["2020-06-17",115],["2020-06-18",111],["2020-06-19",309],["2020-06-20",206],["2020-06-21",137],["2020-06-22",128],["2020-06-23",85],["2020-06-24",94],["2020-06-25",71],["2020-06-26",106],["2020-06-27",84],["2020-06-28",93],["2020-06-29",85],["2020-06-30",73],["2020-07-01",83],["2020-07-02",125],["2020-07-03",107],["2020-07-04",82],["2020-07-05",44],["2020-07-06",72],["2020-07-07",106],["2020-07-08",107],["2020-07-09",66],["2020-07-10",91],["2020-07-11",92],["2020-07-12",113],["2020-07-13",107],["2020-07-14",131],["2020-07-15",111],["2020-07-16",64],["2020-07-17",69],["2020-07-18",88],["2020-07-19",77],["2020-07-20",83],["2020-07-21",111],["2020-07-22",57],["2020-07-23",55],["2020-07-24",60]];
var dateList = data.map(function (item) {
return item[0];
});
var valueList = data.map(function (item) {
return item[1];
});
option = {
color: {
type: 'linear',
x: 0, y: 1,x2:0,y2:0,
colorStops: [{
offset: 0, color: '#00d4ff' // color at 0% position
}, {
offset: 1, color: '#090979' // color at 100% position
}],
global:true
},
// Make gradient line here
visualMap: [{
show: true,
type: 'continuous',
seriesIndex: 0,
min: 0,
max: 400
}],
title: [{
left: 'center',
text: 'Gradient along the y axis'
}],
xAxis: [{
data: dateList,
axisPointer: {
label:{
color:['#5470c6'],
}
},
axisLabel: {
formatter: function (value) {
return moment(value).format("MMM YY");
// And other formatter tool (e.g. moment) can be used here.
}
}
}],
yAxis: [{
type: 'value',
axisPointer: {
label:{
color:['#5470c6'],
}
}
}],
grid: [{
width:'auto',
height:'auto'
}],
tooltip : {
trigger: 'axis',
axisPointer: {
animation: true,
},
formatter: function (params) {
var colorSpan = color => '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + color + '"></span>';
let rez = '<p>' + params[0].axisValue + '</p>';
console.log(params); //quite useful for debug
params.forEach(item => {
// console.log(item); //quite useful for debug
var xx = '<p>' + colorSpan('#00d4ff') + ' ' + item.seriesName + ': ' + item.data + '</p>'
rez += xx;
});
console.log(rez);
return rez;
}
},
series: [{
color:['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
type: 'line',
showSymbol: false,
data: valueList,
// smooth: true,
label:{
show:true,
position:'top'
},
lineStyle:{
color: {
type: 'linear',
x: 0, y: 1,x2:0,y2:0,
colorStops: [{
offset: 0, color: '#00d4ff' // color at 0% position
}, {
offset: 1, color: '#090979' // color at 100% position
}],
global:false
}
}
}]
};
console.log(myChart);
if (option && typeof option === 'object') {
myChart.setOption(option);
}
You need to add gradientColor array to echarts options. Now echart will take care of changing color of tooltip and data point. You can also remove your custom tooltip formatted function.
gradientColor: ["#00d4ff", "#090979"]
Here the complete options object:
var data = [];
var dateList = data.map(function(item) {
return item[0];
});
var valueList = data.map(function(item) {
return item[1];
});
option = {
gradientColor: ["#00d4ff", "#090979"],
// Make gradient line here
visualMap: [
{
show: true,
type: "continuous",
seriesIndex: 0,
min: 0,
max: 400
}
],
title: [
{
left: "center",
text: "Gradient along the y axis"
}
],
xAxis: [
{
data: dateList,
axisPointer: {
label: {
color: ["#5470c6"]
}
},
axisLabel: {
formatter: function(value) {
return moment(value).format("MMM YY");
// And other formatter tool (e.g. moment) can be used here.
}
}
}
],
yAxis: [
{
type: "value",
axisPointer: {
label: {
color: ["#5470c6"]
}
}
}
],
grid: [
{
width: "auto",
height: "auto"
}
],
tooltip: {
trigger: "axis",
axisPointer: {
animation: true
}
},
series: [
{
type: "line",
showSymbol: false,
data: valueList,
// smooth: true,
label: {
show: true,
position: "top"
}
}
]
};

multiple charts js in page but with same tooltips (about last chart)

I have more doughnut charts in one page, every chart have different data but I show the same tooltips. It's tooltips of the last chart. I don't found the problem.
This is js code:
var idList = [];
// --------------------
// Memo ID list...
// --------------------
jQuery('.idKQI').each(function (i) {
idList.push( jQuery(this).text() );
});
var idListLength = idList.length;
// ------------------
// Doughnut loop...
// ------------------
var dataDoughnutChart = {
labels: [
'KO',
'OK'
],
datasets: [{
data: [30,70],
backgroundColor: [
'#DF0101', // red
'#31B404' // green
]
}]
};
var optionsDoughnutChart = {
maintainAspectRatio: false,
responsive: true,
legend: {
display: false
},
tooltips: {
mode: 'dataset'
}
};
var idLav;
var ctxDoughnut;
var labelAdd;
var errati;
var esatti;
for (var i = 0, max = idListLength; i < max; i++) {
idLav = '#' + idList[i] + "_chartDoughnut";
ctxDoughnut = jQuery(idLav);
labelAdd = jQuery(idLav).data("labeladd");
errati = jQuery(idLav).data("errati");
esatti = jQuery(idLav).data("esatti");
dataDoughnutChart.labels[0] = 'Errati' + labelAdd;
dataDoughnutChart.labels[1] = 'Esatti' + labelAdd;
dataDoughnutChart.datasets[0].data[0] = errati;
dataDoughnutChart.datasets[0].data[1] = esatti;
var myDoughnutChart = new Chart(ctxDoughnut, {
type: 'doughnut',
data: dataDoughnutChart,
options: optionsDoughnutChart
});
}
If I have two doughnut chart, in witch in the first chart datasets.data = [10,90], and in the second chart datasets.data = [2,98], the tooltips for all two chart show 'Errati: 2' and 'Esatti: 98'. It's values like the second chart.
I'm also try to use an array for var dataDoughnutChart like:
var myDoughnutChart = new Chart(ctxDoughnut, {
type: 'doughnut',
data: dataDoughnutChart[i],
options: optionsDoughnutChart
});
but don't resolve.
Thanks for your help.
Resolved like below:
// .....
configDoughnutList.push(
{
type: 'doughnut',
data: {
datasets: [{
data: [
30,
70
],
backgroundColor: [
'#DF0101', // rosso
'#31B404' // verde
],
label: 'daughnut_163'
}],
labels: [
'Errati',
'Corretti'
]
},
options: {
responsive: true,
legend: {
display: false
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
mode: 'dataset'
}
}
}
);
configDoughnutList[i].data.datasets[0].data[0] = errati;
configDoughnutList[i].data.datasets[0].data[1] = esatti;
configDoughnutList[i].data.labels[0] = 'Errati' + labelAdd;
configDoughnutList[i].data.labels[1] = 'Esatti' + labelAdd;
window.myDoughnut = new Chart(ctxDoughnut, configDoughnutList[i]);

Chart.js line doesn't fit in

The line which consist of points with maximum doesn't fit in chart... I tried to use responsive, edit height - all the same.
var ctx = document.getElementById('chart').getContext('2d');
var colors = ['#3e95cd', '#8e5ea2', '#3cba9f', '#e8c3b9', '#c45850'];
var datasets = [];
for (var id in data) {
datasets.push({
data: Object.values(data[id].items),
label: data[id].name,
borderColor: colors.pop(),
fill: false
})
}
window.myLine = Chart.Line(ctx, {
type: 'line',
data: {
labels: Object.keys(data[1].items),
datasets: datasets,
},
options: {
responsive: true,
title: {
display: true,
text: _DATE.clone().subtract(_PERIOD, 'days').format('YYYY-MM-DD') + ' - ' + _DATE.format('YYYY-MM-DD')
}
}
});
You have to increase the height of the canvas
For example:
<div style="height: 200px" id="chart"> </div>
or in your css file.
I hope this helps.

Highcharts not showing string value

I'm trying to add localstorage values into highchart series but it doesn't work.
When i print the "newString" value on the console and replace the value for "newString" at the code it works but it doesn't when I use var newString.
Here is the code:
$(document).ready(function () {
var archive,
j = "",
keys = Object.keys(localStorage),
x = keys.length;
var i = 0;
while (i < x) {
archive = JSON.parse(localStorage.getItem(keys[i]));
j += "{ name: " + keys[i] + ", data: [" + archive.username + ", " + archive.email + ", " + archive.password + "]},";
i++;
}
var newString = j.substr(0, j.length - 1);
console.log('newString: ', newString);
Highcharts.chart('container', {
title: {
text: 'Datos ingresados'
},
subtitle: {
text: 'Localstorage'
},
yAxis: {
title: {
text: 'Datos ingresados'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2017
}
},
series: [
newString
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
});
This is what console.log shows:
{ name: 2, data: [12345, 23456, 34567]},{ name: 3, data: [23456, 34567, 45678]},{ name: 4, data: [34567, 45678, 56789]},{ name: 5, data: [45678, 56789, 67890]}
When I change the value of newString for that, it works properly.
Because in the second case, Highcharts see your data as a pure string. So, you need to parse your string.
But first of all, we should create valid json for parsing correctly:
var newString = "{ name: 2, data: [12345, 23456, 34567]}"; //bad json
var json = newString.replace(/(['"])?([a-zA-Z0-9]+)(['"])?:/g, '"$2":');
var goodJson = "[" + json + "]"; //valid json
Now we can create options for the Highcharts:
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: []
};
And push data to series as follows:
$.each(JSON.parse(goodJson), function(i, item) {
options.series.push({
name: item.name,
data: item.data
});
});
And finally initialize Highcharts:
var chart = new Highcharts.Chart(options);
See at Plunker

Highcharts Bar Chart: possible to combine datapoints inside dataLabels?

I have a Highcharts horizontal bar chart with two series. Is it possible to combine the grouped data points into each data label so that they appear together, e.g. 1.00 / 2.3?
CODE:
var labels = [
'AAA/Aaa',
'AA+/Aa1',
'AA/Aa2',
'AA-/Aa3',
'A+/A1',
'A/A2',
'A-/A3'
];
var theData = [
{
name: 'Company 1',
data: [0.576,7.617,12.101,18.839,18.022,7.644,9.72]
},
{
name: 'Company 2',
data: [4.123,12.862,14.561,13.754,12.226,11.135,7.51]
}
];
HIGHCHARTS CONFIG:
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
legend: {
align: 'center',
layout: 'horizontal',
verticalAlign: 'bottom'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter: function() {
var out = '<span class="col-chart-label">';
out += this.y + ' / ' + this.y;
out += '</span>'
return out;
},
useHTML: true
}
}
},
series: theData,
tooltip: {
enabled: false
},
xAxis: {
categories: labels,
labels: {
formatter: false,
overflow: 'justify',
rotation: false
},
reversed: true
}
});
});
The demo is here:
http://jsfiddle.net/dylanmac/RungW/2/
To reiterate, there should be one data label per pair of bars with the top bar as the first value and the bottom bar as the second value, separated by "/"
Thanks a lot.
You can loop through all series and sum values for a specific category, see: http://jsfiddle.net/RungW/3/
formatter: function() {
var out = '<span class="col-chart-label">',
series = this.point.series.chart.series,
p1 = series[0].yData[this.point.x],
p2 = series[1].yData[this.point.x];
out += this.y + ' / ' + (p1 + p2);
out += '</span>'
return out;
},

Categories

Resources