Elastic X axis for stacked barchart, removing the empty bins [dc.js] - d3.js

There is this example that shows how you can make an elastic X axis that removes the empty bins using a fake group and the chart.elasticX(true) method.
I'm trying to make this work with a stacked barchart but I face a problem. I have slightly modified the code of the above example to use a stacked group for the barchart. (I have added an Earned column in the data, made a fake group for it and assigned it to the chart.stack method). But for certain "Earned" values there is a d3.js error:
Uncaught TypeError: Cannot read property '1' of undefined.
#
Update:
This issue is related with this answer which states that "The stack method expects your data to be equally length-ed". It is also related with this answer that proposes the creation of a combined group to overcome the problem.
#
Here is the modified example code
<!DOCTYPE html>
<html lang="en">
<head>
<title>dc.js - Filtering Example</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.0.0/dc.min.css"/>
</head>
<body>
<div class="container">
<script type="text/javascript" src="header.js"></script>
<p>Example demonstrating using a "Fake Group" to remove
the empty bars of an ordinal bar chart when their values drop to zero.</p>
<p>(Note the use of <code>.elasticX(true)</code>
to force calculation of the X domain each round.)</p>
<div id="chart-ring-year"></div>
<div id="chart-hist-spend"></div>
<div id="chart-row-spenders"></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.12/d3.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dc/2.0.0/dc.min.js"></script>
<script type="text/javascript">
var yearRingChart = dc.pieChart("#chart-ring-year"),
spendHistChart = dc.barChart("#chart-hist-spend"),
spenderRowChart = dc.rowChart("#chart-row-spenders");
// use static or load via d3.csv("spendData.csv", function(error, spendData) {/* do stuff */});
var spendData = [
{Name: 'Mr A', Spent: '$40', Earned: '$70', Year: 2011},
{Name: 'Mr B', Spent: '$10', Earned: '$20', Year: 2011},
{Name: 'Mr C', Spent: '$40', Earned: '$40', Year: 2011},
{Name: 'Mr A', Spent: '$70', Earned: '$170', Year: 2012},
{Name: 'Mr B', Spent: '$20', Earned: '$30', Year: 2012},
{Name: 'Mr B', Spent: '$50', Earned: '$30', Year: 2013},
{Name: 'Mr C', Spent: '$30', Earned: '$70', Year: 2013}
];
// normalize/parse data
spendData.forEach(function(d) {
d.Spent = d.Spent.match(/\d+/);
d.Earned = d.Earned.match(/\d+/);
});
function remove_empty_bins(source_group) {
return {
all:function () {
return source_group.all().filter(function(d) {
return d.value != 0;
});
}
};
}
// set crossfilter
var ndx = crossfilter(spendData),
yearDim = ndx.dimension(function(d) {return +d.Year;}),
spendDim = ndx.dimension(function(d) {return Math.floor(d.Spent/10);}),
earnDim = ndx.dimension(function(d) {return Math.floor(d.Earned/10);}),
nameDim = ndx.dimension(function(d) {return d.Name;}),
spendPerYear = yearDim.group().reduceSum(function(d) {return +d.Spent;}),
spendPerName = nameDim.group().reduceSum(function(d) {return +d.Spent;}),
spendHist = spendDim.group().reduceCount(),
earnHist = earnDim.group().reduceCount(),
nonEmptyHist = remove_empty_bins(spendHist)
nonEmptyEarnHist = remove_empty_bins(earnHist)
yearRingChart
.width(200).height(200)
.dimension(yearDim)
.group(spendPerYear)
.innerRadius(50);
spendHistChart
.width(300).height(200)
.dimension(spendDim)
.group(nonEmptyHist)
.stack(nonEmptyEarnHist)
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)
.elasticX(true)
.elasticY(true);
spendHistChart.xAxis().tickFormat(function(d) {return d*10}); // convert back to base unit
spendHistChart.yAxis().ticks(2);
spenderRowChart
.width(350).height(200)
.dimension(nameDim)
.group(spendPerName)
.elasticX(true);
dc.renderAll();
</script>
</div>
</body>
</html>
However if you change the Earned values to
var spendData = [
{Name: 'Mr A', Spent: '$40', Earned: '$70', Year: 2011},
{Name: 'Mr B', Spent: '$10', Earned: '$20', Year: 2011},
{Name: 'Mr C', Spent: '$40', Earned: '$40', Year: 2011},
{Name: 'Mr A', Spent: '$70', Earned: '$170', Year: 2012},
{Name: 'Mr B', Spent: '$20', Earned: '$30', Year: 2012},
{Name: 'Mr B', Spent: '$50', Earned: '$50', Year: 2013}, // This is the only change Earned from '$30' to '$50'
{Name: 'Mr C', Spent: '$30', Earned: '$70', Year: 2013}
]
Then it works fine.
I face the same d3 error for my case so I tried to reproduce it with a simple example.
There is also this related question

Welp, you found the answer already; it's just a matter of applying it.
This is indeed the same question that can be solved with a combined group.
combinedGroup = combine_groups(nonEmptyHist,nonEmptyEarnHist)
function sel_stack(i) {
return function(d) {
return d.value[i];
};
}
spendHistChart
.group(combinedGroup, 'spend', sel_stack(0))
.stack(combinedGroup, 'earn', sel_stack(1))
I don't know of another way to deal with this; d3.stack requires arrays of the same size and dc.js will also assume that the key/value arrays correspond to each other.
Fiddle: http://jsfiddle.net/gordonwoodhull/dwkgud92/3/

Related

How to display current values in pie chart & bar chart labels, like in tooltips?

Please see the image below. The pie chart only shows category 2011, 2012 & 2013. The row bar chart only shows Mr. A, Mr.B & Mr. C.
How can I edit my code below to make the labels display what is shown in the tooltips that are displayed on hover?
I want to display all labels like "2011: 80" instead of "2011" (using the selection to change the value).
Also "2012: 90" instead of "2012", and "2013: 80" instead of "2013".
The rest of charts should also display the names with values. How can I change the code to achieve this?
<!DOCTYPE html>
<html lang="en">
<head>
<title>dc.js - Removing Empty Bars</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://dc-js.github.io/dc.js/css/dc.css"/>
</head>
<body>
<div class="container">
<script type="text/javascript" src="https://raw.githubusercontent.com/dc-js/dc.js/develop/web-src/examples/header.js"></script>
<p>Example demonstrating using a "Fake Group" to remove
the empty bars of an ordinal bar chart when their values drop to zero.</p>
<p>(Note the use of <code>.elasticX(true)</code>
to force calculation of the X domain each round.)</p>
<div id="chart-ring-year"></div>
<div id="chart-hist-spend"></div>
<div id="chart-row-spenders"></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.1.1/d3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dc/4.1.1/dc.js"></script>
<script type="text/javascript">
var yearRingChart = new dc.PieChart("#chart-ring-year"),
spendHistChart = new dc.BarChart("#chart-hist-spend"),
spenderRowChart = new dc.RowChart("#chart-row-spenders");
// use static or load via d3.csv("spendData.csv").then(function(spendData) {/* do stuff */});
var spendData = [
{Name: 'Mr A', Spent: '$40', Year: 2011},
{Name: 'Mr B', Spent: '$10', Year: 2011},
{Name: 'Mr C', Spent: '$40', Year: 2011},
{Name: 'Mr A', Spent: '$70', Year: 2012},
{Name: 'Mr B', Spent: '$20', Year: 2012},
{Name: 'Mr B', Spent: '$50', Year: 2013},
{Name: 'Mr C', Spent: '$30', Year: 2013}
];
// normalize/parse data
spendData.forEach(function(d) {
d.Spent = d.Spent.match(/\d+/);
});
function remove_empty_bins(source_group) {
return {
all:function () {
return source_group.all().filter(function(d) {
return d.value != 0;
});
}
};
}
// set crossfilter
var ndx = crossfilter(spendData),
yearDim = ndx.dimension(function(d) {return +d.Year;}),
spendDim = ndx.dimension(function(d) {return Math.floor(d.Spent/10);}),
nameDim = ndx.dimension(function(d) {return d.Name;}),
spendPerYear = yearDim.group().reduceSum(function(d) {return +d.Spent;}),
spendPerName = nameDim.group().reduceSum(function(d) {return +d.Spent;}),
spendHist = spendDim.group().reduceCount(),
nonEmptyHist = remove_empty_bins(spendHist)
yearRingChart
.width(200).height(200)
.dimension(yearDim)
.group(spendPerYear)
.innerRadius(50);
spendHistChart
.width(300).height(200)
.dimension(spendDim)
.group(nonEmptyHist)
.x(d3.scaleBand())
.xUnits(dc.units.ordinal)
.elasticX(true)
.elasticY(true);
spendHistChart.xAxis().tickFormat(function(d) {return d*10}); // convert back to base unit
spendHistChart.yAxis().ticks(2);
spenderRowChart
.width(350).height(200)
.dimension(nameDim)
.group(spendPerName)
.elasticX(true);
dc.renderAll();
</script>
</div>
</body>
</html>
The tooltip text is controlled by .title(), because title is the SVG tag for tooltips, and the label is controlled by .label().
Pass each one of these a function that takes the data {key, value} and returns the text you want.
The default tooltip/title function is d => d.key + ': ' + d.value.
A lazy way to copy the title function to the label is
yearRingChart
.label(yearRingChart.title())
Or, for more control, define it yourself:
.label(d => d.key + ': ' + d.value)
<!DOCTYPE html>
<html lang="en">
<head>
<title>dc.js - Removing Empty Bars</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://dc-js.github.io/dc.js/css/dc.css"/>
</head>
<body>
<div class="container">
<script type="text/javascript" src="https://raw.githubusercontent.com/dc-js/dc.js/develop/web-src/examples/header.js"></script>
<div id="chart-ring-year"></div>
<div id="chart-hist-spend"></div>
<div id="chart-row-spenders"></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.1.1/d3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dc/4.1.1/dc.js"></script>
<script type="text/javascript">
var yearRingChart = new dc.PieChart("#chart-ring-year"),
spendHistChart = new dc.BarChart("#chart-hist-spend"),
spenderRowChart = new dc.RowChart("#chart-row-spenders");
// use static or load via d3.csv("spendData.csv").then(function(spendData) {/* do stuff */});
var spendData = [
{Name: 'Mr A', Spent: '$40', Year: 2011},
{Name: 'Mr B', Spent: '$10', Year: 2011},
{Name: 'Mr C', Spent: '$40', Year: 2011},
{Name: 'Mr A', Spent: '$70', Year: 2012},
{Name: 'Mr B', Spent: '$20', Year: 2012},
{Name: 'Mr B', Spent: '$50', Year: 2013},
{Name: 'Mr C', Spent: '$30', Year: 2013}
];
// normalize/parse data
spendData.forEach(function(d) {
d.Spent = d.Spent.match(/\d+/);
});
function remove_empty_bins(source_group) {
return {
all:function () {
return source_group.all().filter(function(d) {
return d.value != 0;
});
}
};
}
// set crossfilter
var ndx = crossfilter(spendData),
yearDim = ndx.dimension(function(d) {return +d.Year;}),
spendDim = ndx.dimension(function(d) {return Math.floor(d.Spent/10);}),
nameDim = ndx.dimension(function(d) {return d.Name;}),
spendPerYear = yearDim.group().reduceSum(function(d) {return +d.Spent;}),
spendPerName = nameDim.group().reduceSum(function(d) {return +d.Spent;}),
spendHist = spendDim.group().reduceCount(),
nonEmptyHist = remove_empty_bins(spendHist)
yearRingChart
.width(200).height(200)
.ordinalColors(d3.schemeCategory10)
.label(yearRingChart.title())
.dimension(yearDim)
.group(spendPerYear)
.innerRadius(50);
spendHistChart
.width(300).height(200)
.ordinalColors(d3.schemeCategory10)
// .label(spendHistChart.title())
.dimension(spendDim)
.group(nonEmptyHist)
.x(d3.scaleBand())
.xUnits(dc.units.ordinal)
.elasticX(true)
.elasticY(true);
spendHistChart.xAxis().tickFormat(function(d) {return d*10}); // convert back to base unit
spendHistChart.yAxis().ticks(2);
spenderRowChart
.width(350).height(200)
.ordinalColors(d3.schemeCategory10)
.label(d => d.key + ': ' + d.value)
.dimension(nameDim)
.group(spendPerName)
.elasticX(true);
dc.renderAll();
</script>
</div>
</body>
</html>

Laravel - Leave status is giving wrong result in chartjs BarChart

In my Laravel-5.8 Application I am displaying Employee Leave Status on BarChart using ChartJs
Controller
public function leave()
{
$userCompany = Auth::user()->company_id;
$userId = Auth::user()->id;
$userEmployee = Auth::user()->employee_id;
// All Leave Requests
$allEmployeeLeaves = HrLeaveRequest::select(DB::raw("COUNT(leave_status) as count"))
->where('company_id', $userCompany)
->whereYear('created_at', date('Y'))
->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
->groupBy(DB::raw("MONTH(created_at)"))
->get()->toArray();
$allEmployeeLeaves = array_column($allEmployeeLeaves, 'count');
//Approved Leaves
$approvedLeaves = HrLeaveRequest::select(DB::raw("COUNT(leave_status) as count"))
->where('company_id', $userCompany)
->where('leave_status', '=', 4)
->whereYear('created_at', date('Y'))
->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
->groupBy(DB::raw("MONTH(created_at)"))
->get()->toArray();
$approvedLeaves = array_column($approvedLeaves, 'count');
// Rejected Leaves
$rejectedLeaves = HrLeaveRequest::select(DB::raw("COUNT(leave_status) as count"))
->where('company_id', $userCompany)
->where('leave_status', 3)
->whereYear('created_at', date('Y'))
->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
->groupBy(DB::raw("MONTH(created_at)"))
->get()->toArray();
$rejectedLeaves = array_column($rejectedLeaves, 'count');
return view('leave-default')
->with('allEmployeeLeaves',json_encode($allEmployeeLeaves,JSON_NUMERIC_CHECK))
->with('approvedLeaves',json_encode($approvedLeaves,JSON_NUMERIC_CHECK))
->with('rejectedLeaves',json_encode($rejectedLeaves,JSON_NUMERIC_CHECK));
}
From the Query Above I want to display a Bar Chart for:
All Leave Requests
Approved Leave
Rejected Leave
Actually when leave_status = 3, it is rejected leaves and leave_status = 4 is approved leave.
View
<div class="card-body">
<div class="chart">
<canvas id="leaveBarChart" style="min-height: 250px; height: 450px; max-height: 250px; max-width: 100%;"></canvas>
</div>
</div>
<script src="{{ asset('theme/adminlte3/plugins/chart.js/Chart.min.js') }}"></script>
<script>
var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var data_all_leaves = <?php echo $allEmployeeLeaves; ?>;
var data_approved_leaves = <?php echo $approvedLeaves; ?>;
var data_rejected_leaves = <?php echo $rejectedLeaves; ?>;
var barChartData = {
labels: month,
datasets: [{
label: 'All Leave Requests',
backgroundColor: "#f56954",
data: data_all_leaves
}, {
label: 'Approved Leaves',
backgroundColor: "#00a65a",
data: data_approved_leaves
}, {
label: 'Rejected Leaves',
backgroundColor: "#f39c12",
data: data_rejected_leaves
}]
};
window.onload = function() {
var ctx = document.getElementById("leaveBarChart").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgba(255, 99, 132, 1)',
borderSkipped: 'bottom'
}
},
responsive: true,
maintainAspectRatio : true,
title: {
display: true,
text: 'Monthly Leave Status'
}
}
});
};
</script>
Displayed Result
I expected the Barchart to display:
All Leaves, Rejected Leaves and Approved Leave. However, I have these three (3) observations.
The chart only display All Leave, which is 2. This comprise of Approved Leave (1) and Rejected Leave (1). It didn't display Approved and Rejected Leaves.
All the Leave are in May, but it put them in January
The Leave counts on the BarChart are in decimal places (1.00, 1.10 ...) instaed of 1, 2 ...
How do I corrected all these?
Thank you
Some of your bars may be present in the chart but actually hidden because the yAxis starts at 1. Therefore you should add the following scales.yAxes.ticks definition inside the chart options. This will also solve the problem with the decimals in the yAxis tick labels.
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
...
Make sure also, that the position of the values in individual datasets.data arrays is the same as the corresponding label in the labels array. That way, the bars should appear at the correct position also.

Area chart using dc.js and crossfilter

I have created a line chart using dc.js and crossfilter. The chart currently looks like this:
Required:
I want the legend of active inactive on top left to position below(bottom) of the chart in center and the x-axis tick label should start from Jan to Dec. I am adding my code below. Thank you.
const dateNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var data = [
{date: "2011-11-14T16:17:54Z", quantity: 2, active: 1000, inactive: 100, type: "tab", city: " "},
{date: "2011-11-14T16:20:19Z", quantity: 2, active: 190, inactive: 100, type: "tab", city: "Berlin"},
{date: "2011-11-14T16:28:54Z", quantity: 1, active: 300, inactive: 200, type: "visa", city: " "},
{date: "2011-11-14T16:30:43Z", quantity: 2, active: 90, inactive: 0, type: "tab", city: "Amsterdam"},
{date: "2011-11-14T16:48:46Z", quantity: 2, active: 90, inactive: 0, type: "tab", city: " "},
{date: "2011-11-14T16:53:41Z", quantity: 2, active: 90, inactive: 0, type: "tab", city: " "},
{date: "2011-11-14T16:54:06Z", quantity: 1, active: 100, inactive: 0, type: "cash", city: " "},
{date: "2011-11-14T16:58:03Z", quantity: 2, active: 90, inactive: 0, type: "tab", city: " "},
{date: "2011-11-14T17:07:21Z", quantity: 2, active: 90, inactive: 0, type: "tab", city: " "},
{date: "2011-11-14T17:22:59Z", quantity: 2, active: 90, inactive: 0, type: "tab", city: " "},
{date: "2011-11-14T17:25:45Z", quantity: 2, active: 200, inactive: 0, type: "cash", city: " "},
{date: "2011-11-14T17:29:52Z", quantity: 1, active: 200, inactive: 100, type: "visa", city: ""}
];
data.forEach(function(d){
var tempDate = new Date(d.date);
d.date = tempDate;
})
var facts = crossfilter(data);
var all = facts.groupAll();
//table
var dateDimension = facts.dimension(function(d){ return d.date; });
//line chart
var dateGroup = dateDimension.group().reduceSum(function(d){ return d.active; });
var dateGroupTip = dateDimension.group().reduceSum(function(d){ return d.inactive; });
var minDate = dateDimension.bottom(1)[0].date;
var maxDate = dateDimension.top(1)[0].date;
var lineChart = dc.lineChart("#test")
.width(700)
.height(200)
.brushOn(false)
.margins({top:10,bottom:30,right:10,left:70})
.dimension(dateDimension)
.group(dateGroupTip,"inactive")
.stack(dateGroup,"active")
.renderHorizontalGridLines(true)
.renderArea(true)
.renderDataPoints(true)
// // .interpolate('basis')
// lineChart.xAxis().ticks(d3.timeMonth, 1)
// lineChart.xAxis().tickFormat(d3.timeFormat('%b'))
.clipPadding(data.length)
.legend(dc.legend().y(10).x(0).itemHeight(12).gap(5))
// .xAxis()
// .ticks(d3.time.month, 7)
// .tickFormat(d3.time.format('%e'));
// .xAxis().tickFormat(d3.time. format('%B'))
// .xUnits(d3.time.months)
.x(d3.scaleLinear().domain([minDate,maxDate]))
lineChart.yAxis().ticks(6);
lineChart.xAxis().ticks(12);
dc.renderAll();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="dc.css"/>
<script src="d3.js"></script>
<script src="crossfilter.js"></script>
<script src="dc.js"></script>
</head>
<body>
<div id="test"></div>
<!-- <script src="app.js"></script> -->
<script src="play.js"></script>
</body>
</html>
Looks like you've figured most of it out, and got confused by the D3 version 3 to version 4 API changes?
Many of the lines you have commented out were correct except for these changes - stuff like d3.time.months changing to d3.timeMonths. You're not the only one - these changes caused a lot of confusion for all of us.
The last steps are
Use time scales: .x(d3.scaleTime().domain([minDate,maxDate]))
Round the dates down to the beginning of the month using d3.timeMonth, both in the dimension definition and in the minDate/maxDate calculation, e.g. var dateDimension = facts.dimension(function(d){ return d3.timeMonth(d.date); });
Tell the chart how to calculate the number of points to show: .xUnits(d3.timeMonths)
Format the x axis ticks: lineChart.xAxis().tickFormat(d3.timeFormat('%B'))
You had most of these, only commented out. Probably because you found examples using the D3v3 API, and they caused errors?
As for the legend, dc.js doesn't do anything sophisticated here - you just have to lay it out manually, setting the margins on the chart to allow enough space, and setting x and y on the legend to put the legend where you want it.
I found that
lineChart
.margins({top:10,bottom:60,right:25,left:40});
.legend(dc.legend().y(165).x(325).itemHeight(12).gap(5))
worked pretty well, but you'll have to adjust it to taste (and, unfortunately, when changes to your data cause the sizes of things to change).
Here's a working fiddle.. I took the liberty of changing your example data so that it includes the desired months.
You're going to run into trouble with this design if your data spans multiple years, but I guess you can cross that bridge when you come to it.

nvd3 multiBarChart - d3.scale.log

I'm just starting out with nvd3 (and d3), and am struggling with logarithmic scaling.
With the linear scale there is no problem, but with the log scale, the bars are not drawn and console logs:
Error: Invalid value for <rect> attribute y="NaN"
Problem: http://plnkr.co/edit/Roe6tiYNDeezDEJHNCwj?p=preview
My code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://rawgithub.com/novus/nvd3/master/src/nv.d3.css">
<script src="https://rawgithub.com/novus/nvd3/master/lib/d3.v3.js"></script>
<script src="https://rawgithub.com/novus/nvd3/master/nv.d3.js"></script>
</head>
<body>
<script>
var chart, chart2;
var data = [{
"key": "Test",
"values":
[
{"x": "One", "y": 110},
{"x": "Two", "y": 6},
{"x": "Three", "y": 12052 },
{"x": "Four", "y": 4543},
{"x": "Five","y": 6069},
{"x": "Six","y": 3899 }
]
}];
/*Linear scale*/
nv.addGraph(function () {
chart = nv.models.multiBarChart()
.showControls(false)
.showLegend(false);
chart.multibar
.yScale(d3.scale.linear())
d3.select('#chart svg')
.datum(data)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
/*Log scale - not working*/
nv.addGraph(function () {
chart2 = nv.models.multiBarChart()
.showControls(false)
.showLegend(false);
chart2.multibar
.yScale(d3.scale.log());
d3.select('#chart2 svg')
.datum(data)
.call(chart2);
nv.utils.windowResize(chart2.update);
return chart;
});
</script>
<div id="chart">
<svg></svg>
</div>
<div id="chart2">
<svg></svg>
</div>
</body>
</html>
I've tried adding domain and range values, but to no avail
.yDomain([0, 12500])
.yRange([50, 0]);
Any ideas?
This doesn't work for the current version of D3 because log scales aren't defined at 0 and there are a couple of 0s hardcoded in the NVD3 source. You would have to either modify the NVD3 source or create a composite scale that returns a useful value for 0 to make this work.

Data binding issue with Kendo Widgets

I am using Kendo UI Library.
Trying to bind the data to Grid. But the grid is not getting populated with data.
I have referred required js libraries and styles as well.
<head>
Referred necessary Styles and Scripts are in order
<script src="scripts/jquery.min.js" type="text/javascript"></script>
<script src="scripts/kendo.web.min.js" type="text/javascript"></script>
</head>
<body>
<div id="courses"></div>
<script type="text/javascript">
$(document).ready(function () {
var Courses = [
{Name: "Theory of computation", Credit: 10},
{Name: "Probability and Statistics", Credit: 20},
{Name: "Discrete Maths", Credit: 10},
{Name: "Modern Physics", Credit: 25},
{Name: "Management Information System", Credit: 15 },
{Name: "Game Theory", Credit: 5 }
];
var courseDataSource = new kendo.data.DataSource({datasource: Courses, PageSize: 5});
courseDataSource.read();
$("#courses").kendoGrid({
dataSource: courseDataSource,
columns : [
{ field: "Name", title: "Course Name"} ,
{ field: "Credit", title: "Credits" }
],
scrollable: false,
pageable : true
});
});
</script>
</body>
Could you please help me in fixing the code.
Please change datasource to data and PageSize to pageSize
var courseDataSource =
new kendo.data.DataSource({datasource: Courses, PageSize: 5});
The correct implementation is
var courseDataSource =
new kendo.data.DataSource({data: Courses, pageSize: 5});
Thanks.

Resources