Modify the legend of a double doughnut with chart js - javascript

I'm trying to create a legend for a doughnut chart created with chart js. The problem is I have two doughnut charts stacked and when creating the legend it defaults to the labels of the first.
I want the legend to show up with the blue label as CPU and a green label as MEM.
Currently the labels when hovering on either doughnut is free and used which I'd like to keep.
here is the script used to create the chart
var responseChartLoad = new Chart(responseChartCanvas, {
type: 'doughnut',
data: {
labels: ["Used", "Free"],
datasets: [{
data: [0, 100],
backgroundColor: [
'#42a5f5',
'#eceff1',
],
borderColor: [
'#FFF',
'#FFF'
],
borderWidth: 2
}, {
data: [0, 100],
backgroundColor: [
'#4db6ac',
'#eceff1',
],
borderColor: [
'#FFF',
'#FFF'
],
borderWidth: 2
}]
},
options: {
responsive: true,
cutoutPercentage: 50,
animation: {
animateRotate: true
},
legend: {
display: true,
position: 'bottom'
},
elements: {
center: {
text: 'CPU/MEM',
fontStyle: 'Helvetica', //Default Arial
sidePadding: 50 //Default 20 (as a percentage)
}
}
}
});

To accomplish that you would have to generate custom legend items, which could be done using the generateLabels method of legend­'s labels, as such :
legend: {
labels: {
generateLabels: function() {
return [{
text: 'CPU',
fillStyle: '#42a5f5',
strokeStyle: '#fff'
}, {
text: 'MEM',
fillStyle: '#4db6ac',
strokeStyle: '#fff'
}];
}
}
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var responseChartLoad = new Chart('responseChartCanvas', {
type: 'doughnut',
data: {
labels: ["Used", "Free"],
datasets: [{
data: [10, 100],
backgroundColor: [
'#42a5f5',
'#eceff1',
],
borderColor: [
'#FFF',
'#FFF'
],
borderWidth: 2
}, {
data: [5, 100],
backgroundColor: [
'#4db6ac',
'#eceff1',
],
borderColor: [
'#FFF',
'#FFF'
],
borderWidth: 2
}]
},
options: {
responsive: true,
cutoutPercentage: 50,
animation: {
animateRotate: true
},
legend: {
display: true,
position: 'bottom',
labels: {
generateLabels: function() {
return [{
text: 'CPU',
fillStyle: '#42a5f5',
strokeStyle: '#fff'
}, {
text: 'MEM',
fillStyle: '#4db6ac',
strokeStyle: '#fff'
}];
}
}
},
elements: {
center: {
text: 'CPU/MEM',
fontStyle: 'Helvetica', //Default Arial
sidePadding: 50 //Default 20 (as a percentage)
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="responseChartCanvas"></canvas>

Related

Chart.js: Why are there two y axes in my line graph?

I'm using chart.js to build a line graph. I can't figure out why there are two y-axes on my graph. I also tried changing the color of the tick labels to white but it isn't working either. Thanks for your help! Here's the preview of my code: https://codepen.io/suminohh/pen/vYROrEx
var xValues = ['6 am','8 am','10 am','12 pm','2 pm','4 pm','6 pm','8 pm','10 pm','12 am'];
var yValues = [7,8,8,9,9,9,10,11,14,14,15];
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "white",
borderColor: "white",
data: yValues,
}]
},
options: {
legend: {display: false},
scales: {
xAxes: [{
gridLines: {
color: 'white',
zeroLineColor: 'white',
}}],
yAxes: [
{ticks: {
min: 6,
max:16,
},
color: 'white',
},
{gridLines: {
color: 'white', //give the needful color
zeroLineColor: 'white',
}},
],
}
}
});
Because you have two axes defined for yAxes. Using proper indentation helps notice these:
yAxes: [
{
ticks: {
min: 6,
max:16,
},
color: 'white',
},
{
gridLines: {
color: 'white', //give the needful color
zeroLineColor: 'white',
}
},
],
See how after color you close the object and start another. Put them as one object and you won’t have two axes:
yAxes: [
{
ticks: {
min: 6,
max:16,
},
color: 'white',
gridLines: {
color: 'white', //give the needful color
zeroLineColor: 'white',
}
},
],

i am making a dynamic chart bar in js

this is how my chart.js is looks like.... This is static chart bar And i Have to make this chat dynamic
(function($) {
// "use strict";
var dlabChartlist = function()
{
var screenWidth = $(window).width();
let draw = Chart.controllers.line.__super__.draw;
var chartBar = function()
{
var options =
{
series: [
{
name: 'Project',
data: [50, 58, 70, 40, 10, 70, 20],
// radius: 12,
},
// {
// name: 'Cycling',
// data: [80, 40, 55, 20, 45, 30, 80]
// },
],
chart: {
type: 'bar',
height: 400,
toolbar: {
show: false,
},
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '57%',
endingShape: "rounded",
borderRadius: 12,
},
},
states: {
hover: {
filter: 'none',
}
},
colors:['#FFA26D'],
dataLabels: {
enabled: false,
},
markers: {
shape: "circle",
},
legend: {
show: false,
fontSize: '12px',
labels: {
colors: '#000000',
},
markers: {
width: 18,
height: 18,
strokeWidth: 10,
strokeColor: '#fff',
fillColors: undefined,
radius: 12,
}
},
stroke: {
show: true,
width: 4,
curve: 'smooth',
lineCap: 'round',
colors: ['transparent']
},
grid: {
borderColor: '#eee',
},
xaxis: {
position: 'bottom',
categories: ['Project1', 'Project2', 'Project3', 'Project4', 'Project5', 'Project6', 'Project7'],
labels: {
style: {
colors: '#787878',
fontSize: '13px',
fontFamily: 'poppins',
fontWeight: 100,
cssClass: 'apexcharts-xaxis-label',
},
},
crosshairs: {
show: false,
}
},
yaxis: {
labels: {
offsetX:-16,
style: {
colors: '#787878',
fontSize: '13px',
fontFamily: 'poppins',
fontWeight: 100,
cssClass: 'apexcharts-xaxis-label',
},
},
},
fill: {
type: 'gradient',
gradient: {
shade: 'white',
type: "vertical",
shadeIntensity: 0.2,
gradientToColors: undefined, // optional, if not defined - uses the shades of same color in series
inverseColors: true,
opacityFrom: 1,
opacityTo: 1,
stops: [0, 50, 50],
colorStops: []
}
},
tooltip: {
y: {
formatter: function (val) {
return val + " Days"
}
}
},
};
var chartBar1 = new ApexCharts(document.querySelector("#chartBar"), options);
chartBar1.render();
}
And this is where im showing index.html where i m showing this chart
<div class="tab-pane fade active show" id="monthly">
<div id="chartBar" class="chartBar"></div>
</div>
I don't have enough knowledge about js and i want this chart bar dynamic.....
and i m using mysql
how can i convert it into dynamic chart

How to align multiple x axes in chart.js?

I have to create three line charts that share the same x-axis but are vertically stacked on top of each other with different y-axes.
Here is my current visualization.
Unfortunately, the x-axis tick marks do not line up because of the y-axis labels. How should I go about fixing this?
Just stack the axes:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Black"],
datasets: [{
label: 'Dataset 1',
data: [10, 30, 50, 20, 25, 44, -10],
borderColor: 'red',
backgroundColor: 'red'
},
{
label: 'Dataset 2',
data: [10000, 30000, 50000, 20000, 25000, 44000, -10000],
borderColor: 'blue',
backgroundColor: 'blue',
yAxisID: 'y2',
}
]
},
options: {
scales: {
y: {
type: 'linear',
position: 'left',
stack: 'demo',
grid: {
borderColor: 'red'
},
title: {
display: true,
text: 'hello'
}
},
y2: {
offset: true,
position: 'left',
stack: 'demo',
grid: {
borderColor: 'blue'
},
title: {
display: true,
text: 'hello2'
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.6.0/dist/chart.min.js"></script>
</body>

Highcharts show percentage in the center of the solid gauge chart

I am very new to Highcharts. I am trying to use the solid gauge. The problem is that the percentage text is not present in the center. Is there anyway to put the percentage in the center of the chart?
Here is the code:
$(function () {
Highcharts.chart('container', {
chart: {
type: 'solidgauge'
},
title: {
text: ''
},
tooltip: {
borderWidth: 0,
backgroundColor: 'none',
shadow: false,
style: {
fontSize: '16px'
},
pointFormat: '{series.name}<br><span style="font-size:2em; color: {point.color}; font-weight: bold">{point.y}%</span>',
positioner: function (labelWidth, labelHeight) {
return {
x: 200 - labelWidth / 2,
y: 180
};
}
},
pane: {
center: ['50%', '27%'],
startAngle: 0,
endAngle: 360,
background: [{ // Track for Stand
outerRadius: '62%',
innerRadius: '38%',
backgroundColor: Highcharts.Color(Highcharts.getOptions().colors[2]).setOpacity(0.3).get(),
borderWidth: 0,
}],
},
yAxis: {
min: 0,
max: 100,
lineWidth: 0,
tickPositions: []
},
plotOptions: {
solidgauge: {
borderWidth: '34px',
dataLabels: {
enabled: false
},
linecap: 'round',
stickyTracking: false
}
},
series: [{
name: 'Stand',
borderColor: Highcharts.getOptions().colors[2],
data: [{
color: Highcharts.getOptions().colors[2],
radius: '50%',
innerRadius: '50%',
y: 50
}]
}]
},
});
The x and y in the label option can set the position but I want it to be dynamic.
Secondly I want it to be always shown. Here is the result of the code above.

HighCharts JS - Getting multiple linear underlays on a scatter plot

I'm trying to make some visualisations using the HighCharts javascript library, mainly I'm hoping to make something very similar to what these guys have on their page:
Research Affiliates - 10Yr Expected Risk & Return
Mainly, I'm trying to work out how they managed to get the 2 solid linear areas on the scatter graph that represent the different Sharpe Ratio levels. Is it just a background image, or have they somehow underlayed an area chart under the scatter chart?
Has anybody got any experience with this, or how to code it?
On the web page you are referring to area type series are used to generate triangular shapes in the background.
Area chart demo: http://www.highcharts.com/demo/area-basic
Area chart API reference: http://api.highcharts.com/highcharts#plotOptions.area
Basically, you can combine any kind of chart type.
See their demo of a scatter plot with a regression line.
As an example of a scatter plot combined with a stacked area chart, see the following code and fiddle:
var Y_MAX = 6;
var X_MAX = 5;
$(function () {
$('#container').highcharts({
title: {
text: 'Scatter plot with stacked area ratio chart'
},
plotOptions: {
area: {
stacking: 'normal'
}
},
xAxis: {
min: 0,
max: X_MAX
},
yAxis: {
min: 0,
max: Y_MAX
},
series: [{
type: 'area',
name: 'Ratio',
data: [{x: 0, y: 0}, {x: X_MAX, y: 0.4*Y_MAX}]
}, {
type: 'area',
name: 'Ratio',
data: [{x: 0, y: 0}, {x: X_MAX, y: 0.6*Y_MAX}]
}, {
type: 'scatter',
name: 'Observations',
data: [1, 0.5, 3.8, 5.5, 3.9, 2.2],
marker: {
radius: 8
}
}]
});
});
Fiddle
Thanks for the heads up on how to combine two charts.
What I actually ended up using was the Polygon Plot type rather than an Area Chart.
I also rendered the labels using Chart.renderer.label.
Still tweaking this, but as a whole reference this is my code (minus data taken out)
$(function () {
$('#scatter-plot').highcharts({
chart: {
type: 'scatter',
zoomType: 'xy'
},
title: {
text: 'Expected Asset Return Against Volatility'
},
legend: {
enabled: false
},
xAxis: {
title: {
text: 'Volatility',
enabled: true,
style: {
fontWeight: 'bold',
fontSize: '18px',
fontFamily: 'PT Sans',
}
},
min: 0,
lineWidth: 0,
lineColor: '#bfbfbf',
gridLineWidth: 0,
tickWidth: 0,
labels: {
format: '{value} %',
style: {
fontSize: '14px',
fontFamily: 'Arial',
}
}
},
yAxis: {
title: {
text: 'Real Expected Returns',
style: {
fontWeight: 'bold',
fontSize: '18px',
fontFamily: 'PT Sans',
},
enabled: true
},
gridLineWidth: 0,
lineWidth: 1,
endOnTick: true,
maxPadding: 0,
startOnTick: true,
minPadding: 0,
lineColor: '#bfbfbf',
minRange: 2,
plotLines: [{
color: '#bfbfbf',
width: 1,
value: 0,
zIndex: 5
}],
labels: {
format: '{value} %',
style: {
fontSize: '14px',
fontFamily: 'Arial',
}
}
},
series: [
{
type: 'polygon',
color: 'rgba(100,100,100, 0.1)',
data: [[0, 0], [20, 10], [20, 0]]
},
{
type: 'polygon',
color: 'rgba(100,100,100, 0.1)',
data: [[0, 0], [20, 20], [20, 0]]
},
{type: 'scatter',
marker: {
radius: 10,
symbol: 'circle',
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
dataLabels: {
enabled: true,
x: -8,
y: -8,
fontFamily: 'PT Sans',
color: 'rgba(50, 50, 50, 0.8)',
format: '{series.name}'
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: 'Volatility: {point.x}%<br>Exp. Return: {point.y}%'
},name: 'United-States',color: 'rgba(215, 40, 40, 0.6)',data: [[15.8,5.9]]},
//Rest of the data here, repeating in the same format as above^^
},
function (chart) { // on complete
chart.renderer.label('<div style="font-size:18px;">0.1 Sharpe Ratio</div>',
$(chart.container).width() - 200,
$(chart.container).height() - 150,
true)
.css({
color: 'rgba(0,0,0,0.5)'
})
.add();
chart.renderer.label('<div style="font-size:18px;">0.2 Sharpe Ratio</div>',
$(chart.container).width() - 200,
$(chart.container).height() - 250,
true)
.css({
color: 'rgba(0,0,0,0.5)'
})
.add();
});
});
And it produced this result:
Thanks again for the tips!

Categories