How to Display value in chart js Incline [closed] - laravel

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 days ago.
Improve this question
how to display the point value incline.
I have a problem with ChartJS: I am using Laravel and wanna to show the point value as incline. can you all help a beginner like me
enter image description here
here is my code : im using PHP
enter image description here
$chartjs = app()->chartjs
->name('projectSummaryByTeam')
->type('line')
->size(['width' => 350, 'height' => 200])
->labels($graphInfo[0])
->datasets([
[
"label" => "Acumulative (Plan)",
'data' => $graphInfo[1],
'type' => 'line',
'borderColor' => "blue",
'backgroundColor' => "blue",
'pointBackgroundColor' => "blue",
'pointBorderColor' => "blue",
'yAxisID' => 'first-y-axis',
'order' => 1,
'fill' => false,
],
[
"label" => "Acumulative (Actual)",
'data' => $graphInfo[2],
'type' => 'line',
'backgroundColor' => $graphActualLineColour,
'borderColor' => $graphActualLineColour,
'pointBackgroundColor' => $graphActualLineColour,
'pointBorderColor' => $graphActualLineColour,
'yAxisID' => 'first-y-axis',
'order' => 2,
'fill' => false,
],
])
here is the next..
the option that work as the animation and display the data
->optionsRaw("
{
plugins: {
colorschemes: {
scheme: 'tableau.Tableau10'
},
datalabels: {
display: false
}
},
tooltips: {
mode: 'index',
callbacks: {
label: function (tooltipItem, data) {
var tooltipValue = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return parseInt(tooltipValue).toLocaleString();
}
}
},
animation: {
duration: 0,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.textAlign = 'top';
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
ctx.textBaseline = 'bottom';
// Loop through each data in the datasets
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = parseInt(dataset.data[index]).toLocaleString();
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
},
scales: {
xAxes: [{
gridLines: {
color: [$arra],
}
}],
yAxes: [
{
id: 'first-y-axis',
type: 'linear',
gridLines: {
display:false
},
ticks: {
beginAtZero: true,
userCallback: function(value, index, values) {
return value.toLocaleString(); // this is all we need
},
},
},
]
}
}"
);

Related

Bars moving out x-axis

enter image description hereenter image description hereAm using Echarts on this project .Everything works fine but my stacked bar charts arent working as expected after a scale rendering which increases the x-axis scale .The bars move out of the x-axis as indicated on the screenshot.
here is my code down here
$scope.$watch(attrs.eData, function (newValue, oldValue, scope) {
var legend = [],
sData = [],
data = newValue,
chartName = '';
series = newValue;
var totalSubtitle = 0;
angular.forEach(data, function (val) {
legend.push(val.name);
});
option = {
name: seriesName,
title: {
text: '',
subtext: totalSubtitle,
x: 'center'
},
tooltip: {
trigger: 'item',
axisPointer: {
type: 'shadow'
}
},
xAxis: {
type: 'value',
min: 0,
axisTick: {
show: true
},
axisTick: {
alignWithLabel: false
}
},
yAxis: {
type: 'category',
scale: true,
data: [seriesName],
max: 100,
min: 100,
axisTick: {
show: false
}
},
legend: {
orient: 'horizontal',
bottom: -29,
order: true,
data: legend
},
series: series
};
myChart.setOption(option);
}, true);
$scope.$watch(attrs.eOptions, function (newValue, oldValue) {
option.title.text = newValue.title.text;
option.title.subtext = newValue.title.subtext;
angular.forEach(newValue.series, function (val) {
seriesName = val.name;
});
myChart.setOption(option);
}, true);
myChart.on('click', function (params) {
$scope.SliceSelected(params);
});
$window.onresize = function () {
myChart.resize();
};
}
};
I got some points from your code this may help you out in this issue.
xAxis: {
type: 'value',
min: 0,
axisTick: {
show: true
},
axisTick: {
alignWithLabel: false
}
}
In the above mentioned code axisTick repeated two times
And change the "xAxis" type to "category" and "yAxis" type to "value".
Hope this will fix your issues

Kendo chart change min and max date for CategoryAxis with script

I have a kendo chart that displays a weeks worth of data. Now I want to change the start and end dates when I change a date picker. But I can not figure out how to change the Category Axis start and end date
I have made a separate button to trigger the changing of the min and max value but it always show the initial input.
What I currently have
#(Html.Kendo().DatePicker().Name("startField")
.Events(e => e.Change("startChanged"))
.Value(DateTime.Now.Date.AddDays(-6))
)
<input id="btnRefresh" type="submit" value="#Html.Resource("Refresh")" class="btn btn-default" />
#(Html.Kendo().Chart<ECOnX.Web.Modules.Containers.Mvc.Models.Container
.ContainerDataChartViewModel>()
.Name("dataChart")
.Title(Html.Resource("Week"))
.ChartArea(chartArea => chartArea.Background("transparent"))
.DataSource(ds => ds.Read(read => read.Action("ChartContainerData_Read", "ContainerController").Data("containerReadData")))
.Series(series =>
{
series.Line(model => model.AccuPercentage, categoryExpression: model => model.RecievedAt).Name(Html.Resource("Battery")).Color("#f0ee20");
series.Line(model => model.PercentageFilled, categoryExpression: model => model.RecievedAt).Name(Html.Resource("Filling")).Color("#76c364");
})
.ValueAxis(axis => axis
.Numeric("percentage")
.Min(0)
.Max(100)
.Line(line => line.Visible(false))
)
.CategoryAxis(axiss =>
{ axiss.Date().BaseUnit(ChartAxisBaseUnit.Hours).BaseUnitStep(1).Min(DateTime.Now.Date.AddDays(-6)).Max(DateTime.Now.Date.AddDays(1).AddMilliseconds(-1))
.MajorGridLines(lines => lines.Visible(false)).Labels(labels => labels.Visible(false));
})
.CategoryAxis(axiss =>
{ axiss.Date().BaseUnit(ChartAxisBaseUnit.Days).BaseUnitStep(1).Min(DateTime.Now.Date.AddDays(-6)).Max(DateTime.Now.Date.AddDays(1).AddMilliseconds(-1))
.Labels(labels => labels.DateFormats(formats => formats.Days("D")));
})
.Tooltip(tooltip => tooltip.Visible(true).Shared(true))
)
And the scripts
$(document).ready(function () {
//change event
$("#btnRefresh").click(function () {
var grid = $("#dataChart").data("kendoChart");
var startPicker = $("#startField").data("kendoDatePicker");
grid.options.categoryAxis.min = startPicker.value();
var end = startPicker.value();
end.setDate(end.getDate() + 7);
grid.options.categoryAxis.max = end;
grid.refresh();
grid.dataSource.read();
});
});
function containerReadData() {
var startPicker = $("#startField").data("kendoDatePicker");
return {
containerId: $('#chartidfield').val(),
startDate: startPicker.value()
}
}
function startChanged() {
var grid = $("#dataChart").data("kendoChart");
grid.dataSource.read();
}
</script>
I have solved this by recreating the categoryaxis in the javescript
function SetCategoryRange()
{
var grid = $("#dataChart").data("kendoChart");
var startPicker = $("#startField").data("kendoDatePicker");
var end = new Date(startPicker.value().getTime());
end.setDate(end.getDate() + 7);
var start = kendo.toString(startPicker.value(), "yyyy/MM/dd HH:mm:ss");
var end = kendo.toString(end, "yyyy/MM/dd HH:mm:ss");
grid.setOptions({
categoryAxis: [{
labels: { visible: false },
majorGridLines: { visible: false },
type: "date",
baseUnit: "hours",
baseUnitStep: 1,
min: start,
max: end
},
{
labels: { dateFormats: { days: "D" } },
type: "date",
baseUnit: "days",
baseUnitStep: 1,
min: start,
max: end
}]
});
grid.refresh();
}

How to solve Chart js mismatched x-axes label and value dynamically in Laravel?

I have encountered a problem using chart js when applying it dynamiccally, which means I get a data from my database and output a bar graph using Chart JS. I found this example which works when a value is 0, but on my situation some data on a specific year cannot be found yet on my database, which leads to a null value. How can I set this empty or null value to zero so that I can achieve this example https://jsfiddle.net/17mw40rx/1/. I want also to show my JS code which I copied from the same sample and applied it to my project. The script works fine but when a year data is missing let say no record found in 2002 and 2005, the data are filled automatically by a wrong year data. I hope you understand my problem. Please I need help from someone about this.
JS Script
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>
<script>
var year = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020'];
var female = <?php echo $female; ?>;
var male = <?php echo $male; ?>;
var entranceDataset = {
label: 'Female',
type: 'bar',
yAxesID : "y-axis-1",
data: female,
backgroundColor: 'rgba(0, 204, 0, 0.2)',
borderColor: 'rgba(0, 204, 0,1)',
borderWidth: 1
};
var dataset = [];
dataset.push(entranceDataset);
var exitDataset = {
label: 'Male',
type: 'bar',
yAxesID : "y-axis-1",
data: male,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
};
dataset.push(exitDataset);
var ctx = $('#enrollcanvas');
mainThroughputChart = new Chart(ctx, {
type: 'bar',
data: {
labels: year,
datasets: dataset
},
options: {
scales: {
xAxes : [{
gridLines : {
display : false
},
scaleLabel: {
display: true,
labelString: 'Year'
}
}]
},
}
});
</script>
Laravel Controller and query
$female = Enroll::select(DB::raw("SUM(tot_enroll) as count"))
->orderBy(DB::raw('sy'))
->groupBy(DB::raw("(sy)"))
->where('gender','=', 'Female')
->get()->toArray();
$female = array_column($female, 'count');
$male = Enroll::select(DB::raw("SUM(tot_enroll) as count"))
->orderBy(DB::raw('sy'))
->groupBy(DB::raw("(sy)"))
->where('gender','=', 'Male')
->get()->toArray();
$male = array_column($male, 'count');
return view('home')
->with('female',json_encode($female,JSON_NUMERIC_CHECK))
->with('male',json_encode($male,JSON_NUMERIC_CHECK));
Blade Page
<canvas id="enrollcanvas" name="enrollcanvas" height="280" width="600"></canvas>
Actual Bar Chart Result
Database Table where the bar chart is based from
I think the problem with mismatched data of $female and $male with JS year variable.
var year = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020'];
var female = <?php echo $female; ?>;
var male = <?php echo $male; ?>;
Pass the '0' if $female OR $male doesn't have value for each year(Let's say 2000). So your $female and $male should be like:
var year = ['2000','2001','2002','2003', '2004'...];
var female = ['0','34', '0','65', '54',...];
var male = ['0','75', '0','34', '0',...];
Update
Try this below code with full snippet of controller side. Replace enroll with your database table name into this query.
$rsltEnrollData = DB::table('enroll')->selectRaw('sy as sy, gender, SUM(tot_enroll) as count')
->groupBy('sy')
->orderBy('sy')
->get();
$arrFemale = array();
$arrMale = array();
$arrYearData = array();
foreach($rsltEnrollData as $key => $objEnrollData){
if(!isset($arrYearData[$objEnrollData->sy])){
$arrYearData[$objEnrollData->sy]['Male'] = 0;
$arrYearData[$objEnrollData->sy]['Female'] = 0;
}
$arrYearData[$objEnrollData->sy][$objEnrollData->gender] = $objEnrollData->count;
$arrFemale = $arrYearData[$objEnrollData->sy]['Female'];
$arrMale = $arrYearData[$objEnrollData->sy]['Male'];
}
Debug
foreach($rsltEnrollData as $key => $objEnrollData){
print('<pre style="color:red;">');
print_r($objEnrollData);
print('</pre>');
}
exit;
this is a snippet of the script in my project. maybe a little different, but maybe someone needs it. and hope it helps in configuring chart js with laravel and database
JAVASCPT
$(document).ready(function() {
var statistics_chart = document.getElementById("myChart").getContext('2d');
fetch("{{url('chart')}}")
.then(response =>response.json())
.then(json=>{
var myChart = new Chart(statistics_chart, {
type: 'line',
data: {
labels: json.labels,
datasets: json.dataset,
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
// display: false,
drawBorder: false,
color: '#f2f2f2',
},
ticks: {
beginAtZero: true,
stepSize: 10000,
}
}],
xAxes: [{
gridLines: {
display: false,
tickMarkLength: 15,
}
}]
},
}
});
})
});
Controller
public function chart()
{
$data = Kas::select([
DB::raw("SUM(debit) as total_debit"),
DB::raw("SUM(kredit) as total_kredit"),
DB::raw("MONTH(created_at) as bln"),
// DB::raw("YEAR(created_at) as year")
])
->whereYear('created_at', 2022)
->groupBy([
'bln'
])
->orderBy('bln')
->get();
$arrBln = [1 => 'Jan','Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
$totalD = $totalK = [];
foreach ($data as $tot) {
$totalD[$tot->bln] = $tot->total_debit;
$totalK[$tot->bln] = $tot->total_kredit;
}
foreach ($arrBln as $month =>$name){
if(!array_key_exists($month, $totalD)){
$totalD[$month]= 0;
}
if(!array_key_exists($month, $totalK)){
$totalK[$month]= 0;
}
}
ksort($totalD);
ksort($totalK);
return[
'labels' => array_values($arrBln),
'dataset' => [
[
'label' => 'Pemasukan',
'data' => array_values($totalD),
'borderWidth'=> 2,
'backgroundColor'=> 'rgba(63,82,227,.8)',
'borderWidth' => 0,
'borderColor' =>'transparent',
'pointBorderWidth' => 0,
'pointRadius' => 3.5,
'pointBackgroundColor' => 'transparent',
'pointHoverBackgroundColor' => 'rgba(63,82,227,.8)',
],
[
'label' => 'Pengeluaran',
'data' => array_values($totalK),
'borderWidth'=> 2,
'backgroundColor' => 'rgba(254,86,83,.7)',
'borderWidth' => 0,
'borderColor' =>'transparent',
'pointBorderWidth'=> 0,
'pointRadius'=> 3.5,
'pointBackgroundColor'=> 'transparent',
'pointHoverBackgroundColor'=> 'rgba(254,86,83,.8)',
],
]
];
}

Handsontable checkbox's not working

Real simple, I've been trying to get the checkbox type to render on my list, but all I get is the value "no." Here's my settings object. Am I doing something wrong? The list renders perfectly and works properly in terms of conditional coloring, etc., just no checkboxes. HELP! and thank you.
settings = {
data: bulkListData
,dataSchema: {name: {first: null, last: null}, email: null,status: null,action: null}
,colHeaders: ['First Name', 'Last Name', 'Email','Status','Action']
,columns: [
{data: 'name.first'},
{data: 'name.last'},
{data: 'email'},
{data: 'status'},
{data: 'action'
,type: 'checkbox'
,checkedTemplate: 'yes'
,uncheckedTemplate: 'no'
}
]
,colWidths:[200,200,300,120,120]
,startRows: 5
,startCols: 5
,minRows: 5
,minCols: 5
,maxRows: 10
,maxCols: 5
,minSpareRows: 5
,autoWrapRow:true
,contextMenu: true}
I put your sample code in a fiddle and it works for me.
The only thing I needed was to fill in the bulkListData accordingly, otherwise everything is exactly like yours. Perhaps you are making the mistake exactly there - are your action properties in this array in the form of yes/no string?
I have a renderer that changes the color of a column. When this renderer is used the check boxes change to 'yes'/'no'.
When the renderer is not used the checkboxes show.
$(document).ready(function () { function getCompData() {
return [
{Comp: "Annually", year: 2006, Retirement: 'yes'},
{Comp: "Monthly", year: 2008, Retirement: 'yes'},
{Comp: "Quarterly", year: 2011, Retirement: 'no'},
{Comp: "Semi-Annually", year: 2004, Retirement: 'yes'},
{Comp: "Semi-Monthly", year: 2011, Retirement: 'no'}
];}function cellColorRenderer(instance, td, row, col, prop, value, cellProperties) {
Handsontable.TextCell.renderer.apply(this, arguments);
if (col === 1) {
td.style.textAlign = 'right';
td.style.backgroundColor = "#ccffcc";
}
}var example2 = document.getElementById('example2'); var hot2 = new Handsontable(example2,{ data: getCompData(),
startRows: 7,
startCols: 4,
colHeaders: ["Comp", "Year", "401K"],
colWidths: [120, 50, 60],
columnSorting: true,
columns: [
{
data: "Comp"
},
{
data: "year",
type: 'numeric'
},
{
data: "Retirement",
type: "checkbox",
checkedTemplate: 'yes',
uncheckedTemplate: 'no'
}
], cells:
function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = cellColorRenderer;
return cellProperties;
}, }); });
Here is the code in jsfiddle
http://jsfiddle.net/w42cp1y8/1/
Just use CheckboxRenderer instead TextRenderer:
$element.handsontable( {
cells: function( row, col, prop ) {
return {
renderer: function( instance, td, row, col, prop, value, cellProperties ) {
Handsontable.renderers.CheckboxRenderer.apply( this, arguments );
td.style.backgroundColor = value ? 'red' : 'white';
td.style.textAlign = 'center';
},
type: 'checkbox'
};
}
} );
jExcel is an alternative to handsontable. The example below is using a checkbox column type:
data = [
['Brazil', 'Classe A', 'Cheese', 1, '2017-01-12'],
['Canada', 'Classe B', 'Apples', 1, '2017-01-12'],
['USA', 'Classe A', 'Carrots', 1, '2017-01-12'],
['UK', 'Classe C', 'Oranges', 0, '2017-01-12'],
];
$('#my').jexcel({
data:data,
colHeaders: [ 'Country', 'Description', 'Type', 'Stock', 'Next purchase' ],
colWidths: [ 300, 80, 100, 60, 120 ],
columns: [
{ type: 'text' },
{ type: 'text' },
{ type: 'dropdown', source:[ {'id':'1', 'name':'Fruits'}, {'id':'2', 'name':'Legumes'}, {'id':'3', 'name':'General Food'} ] },
{ type: 'checkbox' },
{ type: 'calendar' },
]
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jexcel/1.2.2/css/jquery.jexcel.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jexcel/1.2.2/js/jquery.jexcel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jexcel/1.2.2/js/jquery.jcalendar.min.js"></script>
<div id="my"></div>

Display chart inside KendoUI Grid

I want to display a KendoUI DataViz grid inside of a KendoUI Grid (display a Kendo chart inside of the Kendo Grid) and I am floundering in the wind on this one. I'm thinking that I need to be working in either the Template or ClientTemplate area of the grid, but I can't even get the most simple of controls to display.
Here is where I am so far...
#(Html.Kendo().Grid<StructurePurchaseDTO>()
.Name("someGrid")
.Columns(c =>
{
c.Bound(x => x.Structure)
.Groupable(true);
c.Bound(x => x.DomesticRatingEffect)
//.ClientTemplate("#=createChart(data)#");
//.Template(#<text>$('#numericTemplate').html()</text>);
//.ClientTemplate("#=createChart(data)#");
})
//....removed for brevity
.DataSource(ds => ds
.Ajax()
.PageSize(10)
.Events(e=>
{
e.Change("Grid_Changed");
})
.Read(r => r.Action("GetData", "Home"))
.Model(m=>m.Id(x =>x.SimulationStructureID))
)
)
//this comes direct from Telerik
function createChart(data) { //I added data b/c I will eventually need to wire this up to a DB
$("#chart").kendoChart({
title: {
text: "Gross domestic product growth /GDP annual %/"
},
legend: {
position: "top"
},
seriesDefaults: {
type: "column"
},
series: [{
name: "India",
data: [3.907, 7.943, 7.848, 9.284, 9.263, 9.801, 3.890, 8.238, 9.552, 6.855]
}, {
name: "Russian Federation",
data: [4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247, -7.832, 4.3, 4.3]
}, {
name: "Germany",
data: [0.010, -0.375, 1.161, 0.684, 3.7, 3.269, 1.083, -5.127, 3.690, 2.995]
}, {
name: "World",
data: [1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333, -2.245, 4.339, 2.727]
}],
valueAxis: {
labels: {
format: "{0}%"
},
line: {
visible: false
},
axisCrossingValue: 0
},
categoryAxis: {
categories: [2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011],
line: {
visible: false
},
labels: {
padding: { top: 145 }
}
},
tooltip: {
visible: true,
format: "{0}%",
template: "#= series.name #: #= value #"
}
});
}
#(Html.Kendo().Grid<StructurePurchaseDTO>()
.Name("someGrid")
.Columns(c =>
{
c.Bound(x => x.Structure)
.Groupable(true);
c.Bound(x => x.ResourceRequirements)
.ClientTemplate("#=ResourceRequirementText(data)#")
.Groupable(false);
c.Bound(x => x.DomesticRatingEffect)
.ClientTemplate("<div class='chart' style='width: 200px; height: 200px;'></div>");
})
.Pageable(p => p.Numeric(false)
.ButtonCount(5)
.Refresh(true)
.Input(false)
.Info(true)
.Enabled(true)
)
.Events(e =>
{
e.DataBound("Grid_DataBound");
})
.Reorderable(r => r.Columns(true))
.Resizable(r => r.Columns(true))
.Sortable()
.Groupable()
.DataSource(ds => ds
.Ajax()
.PageSize(5)
.Events(e =>
{
e.Change("Grid_Changed");
})
.Read(r => r.Action("GetStructuresWithGraphs", "Structure"))
.Model(m => m.Id(x => x.SimulationStructureID))
)
)
function Grid_DataBound(e) {
var data = this.dataSource.view();
//this.tbody.find("script").each(function () {
// //debugger;
// eval($(this).html());
//});
//debugger;
$('.chart').each(function () {
var chart = $(this);
chart.kendoChart({
chartArea:{
background: "transparent",
},
legend: {
visible: false,
position: "top"
},
seriesDefaults: {
type: "column",
stack: false
},
series: [{
name: "Culture",
data: [7],
color: "lime"
}, {
name: "Education",
data: [2],
color: "#ff0000",
}, {
name: "Environment",
data: [1],
}, {
name: "Health",
data: [0],
color: "red",
}, {
name: "Safety",
data: [-5],
color: "green",
}, {
name: "Welfare",
data: [0],
}],
valueAxis: {
labels: {
visible: false,
format: "{0}"
},
line: {
visible: false
},
majorTicks: {
color: "#000",
width: 0
},
majorGridLines: {
width: 0,
},
axisCrossingValue: 0,
},
categoryAxis: {
line: {
visible: true
},
majorGridLines: {
width: 0,
},
majorTicks: {
visible: false,
//width: 0
},
labels: {
}
},
tooltip: {
visible: true,
format: "{0}",
template: "#= series.name #: #= value #"
}
});
});
}

Resources