How do I set the style for the legend data differently per dataset with Chart.js? - html5-canvas

I have created a chart with Chart.js, and I now need to show the data in the legend differently per the two different datasets.
How do I show the first dataset 'Low/High Range Limit' in the classic rectangle/fill style and the dataset 'Patient Results' in the point style?
(Bonus: Currently, I'm showing the second dataset near-correctly. I also want to completely fill the circle with the solid 'steelblue' color, not with transparency.)
(I would provide an image but I need at least 10 reputation to post them.)
<style>
.chart-container { width: 550px }
</style>
<div class="chart-container">
<canvas id="myChart" width="2" height="1"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script>
var context = document.getElementById('myChart');
var myChart = new Chart(context, {
type: 'line',
data: {
labels: ['(A)', '(B)', '(C)', '(D)'],
datasets: [
{
label: 'Patient Results',
data: [40, 230, 30, 60],
borderColor: 'steelblue',
borderWidth: 2,
pointBackgroundColor: 'steelblue',
fill: false,
spanGaps: true // if true, lines will be drawn between points with no or null data. if false, points with NaN data will create a break in the line.
},
{
data: [0, 30, 20, 20], // representing the low range only
borderColor: '#222',
borderWidth: 2,
pointRadius: 0,
fill: true,
backgroundColor: '#fff'
},
{
label: 'Low/High Range Limit',
data: [60, 150, 50, 40], // representing the high range only
borderColor: '#222',
borderWidth: 2,
pointRadius: 0,
fill: true,
backgroundColor: '#c2e8f5'
}
]
},
options: {
elements: {
line: {
tension: 0 // disables bezier curves
}
},
legend: {
labels: {
boxWidth: 6,
filter: function(legendItem, chartData) {
if (legendItem.datasetIndex === 1) {
return false;
}
return true;
},
usePointStyle: true
},
position: 'right',
reverse: true // shows 'Low/High Range Limit' first
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>

Related

how to display multiple sum with chart js and laravel?

I have three table
Table drics
Table country_dric
Table Countries
I just display country name with sum legal from table drics.
I want to display sum column legal, illegal, applicant and mandatory from table drics with country name.
How to display the sum of each column from table drics?
my controller
$drics =DB::table('countries')
->join('country_dric','countries.id','country_dric.country_id')
->join('drics','drics.id','country_dric.dric_id')
->select('name',\DB::raw('sum(legal) as sum'))->groupby('name')
->whereYear('drics.created_at', $year)->get();
$dric_title=[];
$dric=[];
foreach ($drics as $key => $value) {
$dric_title[$key]=$value->name;
$dric[$key]=$value->sum;
}
return view('home.home', compact(' 'dric', 'dric_title'));
js Code
<script>
var ctx = document.getElementById('dric').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($dric_title),
datasets: [{
label: '# ',
data: #json($dric),
backgroundColor: "rgba(0,31,68,0.8)",
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
Try this
Your controller:
$drics =DB::table('countries')
->join('country_dric','countries.id','country_dric.country_id')
->join('drics','drics.id','country_dric.dric_id')
->select('name',\DB::raw('sum(legal) as legal_sum')
,\DB::raw('sum(ilegal) as ilegal_sum')
,\DB::raw('sum(applicant) as applicant_sum')
,\DB::raw('sum(mandatory) as mandatory_sum'))->groupby('name')
->whereYear('drics.created_at', $year)->get();
$dric_title=[];
$dric=[];
foreach ($drics as $key => $value) {
$dric_title[$key]=$value->name;
$dric['legal'][$key]=$value->legal_sum;
$dric['ilegal'][$key]=$value->ilegal_sum;
$dric['applicant'][$key]=$value->applicant_sum;
$dric['mandatory'][$key]=$value->mandatory_sum;
}
return view('home.home', compact(' 'dric', 'dric_title'));
js code:
<script>
var ctx = document.getElementById('dric').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($dric_title),
datasets: [{
label: 'Legal',
data: #json($dric['legal']),
backgroundColor: "rgba(0,31,68,0.8)",
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Ilegal',
data: #json($dric['ilegal']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Applicant',
data: #json($dric['applicant']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Mandatory',
data: #json($dric['mandatory']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
You can use #foreach loop if you want too

How to pass data in Laravel with Chart.js

I want to display total of men and woman from learnings table in chart using Chartjs in Laravel.
My controller
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
$learning = $men_learning + $women_learning ;
return view('home', compact('learning'));
}
My script in blade view.
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['total'],
datasets: [{
label: '# of Votes',
data: [12],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
How can I propagate loaded statistic from my script to the chart?
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
return view('home', compact('men_learning', 'women_learning'));
}
<script type="text/javascript">
$(function(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Men', 'Women'],
datasets: [{
label: 'Men',
data: [{!!$men_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(40,167,69,1)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0 ,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(254,86,83,.8)',
},
{
label: 'Women',
data: [{!!$women_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(220,53,69,.8)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(63,82,227,.8)',
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
display: true,
drawBorder: false,
color: '#f2f2f2',
},
ticks: {
beginAtZero: true,
stepSize: 100,
callback: function(value, index, values) {
return value;
}
}
}],
xAxes: [{
gridLines: {
display: false,
tickMarkLength: 15,
}
}]
},
}
});
});
</script>

How to configure linear labels in Time Cartesian Chartjs?

I need to show labels on the x-axis every 2 hours (0h, 2h, 4h...). What am I missing?
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//labels: ['0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h', '0h'],
datasets: [{
label: 'AAA1111',
//xAxisID: 'Hora',
//yAxisID: 'Velocidade',
data: [{
t: new Date("2015-3-15 12:30"),
y: 12
},
{
t: new Date("2015-3-15 14:40"),
y: 45
},
{
t: new Date("2015-3-15 17:50"),
y: 77
}
],
borderColor: 'rgba(255, 0, 0, 1)',
borderWidth: 4,
fill: false,
lineTension: 0,
lineJoint: "round",
spanGaps: true
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
time: {
unit: 'hour',
//stepSize: 24??
},
ticks: {
source: 'data'
}
}]
}
}
});
</script>
The chart plots Time x Velocity.
Two small changes will achieve the desired result:
set stepSize: 2 to 'show labels on X axis every 2 hours (0h, 2h, 4h...)'
remove ticks: { source: 'data' } as that:
generates ticks from data (including labels from data {t|x|y} objects)"
Here's a working example based on the posted code:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//labels: ['0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h', '0h'],
datasets: [{
label: 'AAA1111',
//xAxisID: 'Hora',
//yAxisID: 'Velocidade',
data: [{
t: new Date("2015-3-15 12:30"),
y: 12
},
{
t: new Date("2015-3-15 14:40"),
y: 45
},
{
t: new Date("2015-3-15 17:50"),
y: 77
}
],
borderColor: 'rgba(255, 0, 0, 1)',
borderWidth: 4,
fill: false,
lineTension: 0,
lineJoint: "round",
spanGaps: true
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
time: {
unit: 'hour',
stepSize: 2
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

How to change path fill color for Kendo bar / line chart?

Click here for demo - https://dojo.telerik.com/#rikinshah/EQiMupoG
I have lots of elements for navigation in headers and icon buttons in footer. all of them are using svg > path elements.
I want to change color for all path elements except Kendo Chart which also contains path elements.
In css I use this to make all to use same color :
path {
fill: #4b4c4c
}
but this also changes color for Kendo chart background.
I tried using :not selector for div ID to fill path for kendo and also tried
chartArea: {
background: "#4b4c4c",
},
path: {
fill: "#4b4c4c"},
fill: {
color: "4b4c4c"}
none of this changes path for svg element in kendo graph.
<div id="kendoChart" class="demo-section k-content wide" style="margin-left: -3px;">
<div id="chart"></div>
</div>
function createChart() {
$("#chart").kendoChart({
theme: "flat",
chartArea: {
background: "transparent",
},
legendItemClick: function (e) {
e.preventDefault();
},
seriesDefaults: {
type: "column",
width: 90,
gap: 1,
},
legend: {
position: "bottom",
spacing: 15,
labels: {
font: "12px sans-serif",
color: "#7F7F7F"
},
},
series: [{
data: [parseFloat(($('#room-revenue1').text()).replace(/,/g, "")),
parseFloat(($('#room-revenue2').text()).replace(/,/g, "")),
parseFloat(($('#room-revenue3').text()).replace(/,/g, "")),
parseFloat(($('#room-revenue4').text()).replace(/,/g, "")),
parseFloat(($('#room-revenue5').text()).replace(/,/g, "")),
parseFloat(($('#room-revenue6').text()).replace(/,/g, "")),
parseFloat(($('#room-revenue7').text()).replace(/,/g, "")), ],
name: "Room Revenue",
color: "#4472c3",
width: 500,
tooltip: {
visible: true,
template: "#= series.name #: #= kendo.format('{0:C2}',value) #",
font: "12px sans-serif",
},
}, {
type: "line",
data: [$('#rooms-sold1').text(),
$('#rooms-sold2').text(),
$('#rooms-sold3').text(),
$('#rooms-sold4').text(),
$('#rooms-sold5').text(),
$('#rooms-sold6').text(),
$('#rooms-sold7').text()],
name: "Room Sold",
color: "#12ccbe",
axis: "Rooms Sold",
width: 2,
markers: { visible: true },
tooltip: {
visible: true,
template: "#= series.name #: #= value #",
font: "12px sans-serif",
},
}],
render: function (e) {
var el = e.sender.element;
el.find("text:contains(Room Revenue)")
.parent()
.prev("path")
.attr("stroke-width", 3);
el.find("text:contains(Room Sold)")
.parent()
.prev("path")
.attr("stroke-width", 0);
},
valueAxes: [
{
visible: false,
majorGridLines: {
visible: true,
width: 0.5,
dashType: "solid",
color: "#ededed"
}
},
{
name: "Rooms Sold",
color: "#4e4141",
visible: false,
line: { visible: false },
majorGridLines: {
visible: false
},
}],
categoryAxis: {
categories: [($('#date1').text()).substring(0, 3),
($('#date2').text()).substring(0, 3),
($('#date3').text()).substring(0, 3),
($('#date4').text()).substring(0, 3),
($('#date5').text()).substring(0, 3),
($('#date6').text()).substring(0, 3),
($('#date7').text()).substring(0, 3)],
labels: {
font: "12px sans-serif",
color: "#7F7F7F"
},
majorGridLines: {
visible: false,
},
},
});
}
$(document).ready(createChart);
$(document).bind("kendo:skinChange", createChart(), 400);
I want to keep kendo chart background color / path fill color unchanged.

set bar width- kendo bar chart using gap and spacing?

I need some help to set the width of the bars in kendo bar charts when the number of bars reduces.
Here is the jsFiddle link i am working on: http://jsfiddle.net/An59E/44/
In this example, there are 2 kendo bar charts, 1 has 6 bars and the other has 12 bars.
In the second graph the bars width is fine. Now when i remove 2 bars i need the same width of bars, instead the default behavior of the kendo is to resize bars. by setting the spacing and the gap values, the bars should resize. In this example, i have set the spacing and gaps value in series defaults attribute but it doesn't look like its working. Now the question is , how to change the width of the bars?
HMTL code:
<div id="chart1">
</div>
<div id="chart2">
</div>
JS code:
var series1= [70, 60, 40];
var series2= [-50, 40, 20];
var series3= [60, 60, -90, 60, 10, 50];
var series4= [60, 20, 20, 50, 40, 10];
$("#chart1").kendoChart({
seriesDefaults:
{
type: "column",
stack: true,
width:2,
gap: 50,
},
series:
[
{
data: series1,
color: "#00CC00",
negativeColor: "#CC0000",
spacing: 0
},
{
data: series2,
color: "#CCCCCC"
}
],
plotArea:
{
border:
{
color: "#CCCCCC",
width: 1
}
},
chartArea:
{
border:
{
color: "#CCCCCC",
width: 1
},
height: 300
},
categoryAxis:
{
pane: "top-pane",
color: "#0099FF",
majorGridLines:
{
visible: true,
},
line:
{
width: 3,
},
plotBands:
[
{from: 0, to:1, color: "#CCCCCC"},
],
},
seriesDefaults:
{
type: "column",
labels:
{
visible: true,
color: "green"
},
},
valueAxis:
{
title:
{
text: "A"
},
majorGridLines:
{
visible: false
},
labels:
{
visible: false,
},
line:
{
visible: false
}
},
tooltip: {
visible: true,
/*format: "{0}"*/
template: "Institutional Results:#=value#<br/>Institutional Target:#=value#<br/>"
}
});
$("#chart2").kendoChart({
series:
[
{
data: series3,
color: "#00CC00",
negativeColor: "#CC0000",
spacing: 0
},
{
data: series4,
color: "#CCCCCC"
}
],
plotArea:
{
border:
{
color: "#CCCCCC",
width: 1
}
},
chartArea:
{
border:
{
color: "#CCCCCC",
width: 1
},
height: 300,
},
categoryAxis:
{
pane: "top-pane",
color: "#0099FF",
majorGridLines:
{
visible: true,
},
line:
{
width: 3,
},
plotBands:
[
{from: 0, to:1, color: "#333333"},
],
/*categories: [2005, 2006, 2007, 2008, 2009, 2010],
labels:
{
margin:
{
top: 100,
}
},*/
},
seriesDefaults:
{
type: "column",
labels:
{
visible: true,
color: "green"
},
},
valueAxis:
{
title:
{
text: "O"
},
majorGridLines:
{
visible: false
},
labels:
{
visible: false,
},
line:
{
visible: false
}
},
tooltip: {
visible: true,
/*format: "{0}"*/
template: "Institutional Results:#=value#<br/>Institutional Target:#=value#<br/>"
}
});
Thanks.
just replace below code snippet in javascript and you are done!
seriesDefaults:
{
type: "column",
labels:
{
visible: true,
color: "green"
},
gap: 5,
},
In above code I have added gap value to define gap of bars which leads to make them thin which you want.
Please refer to below js fiddle.
http://jsfiddle.net/An59E/134/
Please let me know if you face any difficulty to implement the same.

Resources