Reputation: 1044
I have a line chart with dynamic data make by c3js chart library.
In that chart, I already show data depend on date with timeseries. Here is the sample of chart.
Now I add three button to show data in chart by day
,month
and year
. When I click day
button, I want to show data only day by day. And the year
and month
button are also too.
The main point is, I want to change x-axis date format dynamically when I click day
, month
and year
button.
So I query data from database for each day, month and year. But the problem is, when I show data in chart, I need to change date format dynamically in x-axis. So, I try like this,
<?php
if(isset($_POST['btn_day'])) {
$sql = "......."
$query = ........;
//query data day by day just like DATE_FORMAT(date, '%d') as date
.
$format = '%d';
}elseif(isset($_POST['btn_month'])) {
$sql = "......."
$query = ........;
//query data for each month just like DATE_FORMAT(date, '%M') as date
.
$format = '%m';
}elseif(isset($_POST['btn_year'])) {
$sql = "......."
$query = ........;
//query data for each year just like DATE_FORMAT(date, '%Y') as date
.
$format = '%Y';
}else {
$sql = "......."
$query = ........;
.
.
$format = '%Y-%m-%d';
}
?>
<script>
var f = <?php echo "'".$format."'"?>; //'%Y-%m-%d'
console.log(f);
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'date',
json:<?php echo json_encode($data);?>,
mimeType: 'json',
keys: {
x: 'date',
value: <?php echo json_encode($names)?>
},
type: 'line',
},
axis: {
x: {
type: 'timeseries',
tick:{
format: function(f){
if(f == "%d"){
return d3.getDay();
}else if(f == "%m"){
return d3.getMonth();
}else if(f == "%Y"){
return d3.getFullYear();
}else{
return '%Y-%m-%d';
}
},
rotate: 75,
}
}
},
});
</script>
But I don't get correct result in chart. I know I was wrong in this part,
tick:{
format: function(f){
if(f == "%d"){
return d3.getDay();
}else if(f == "%m"){
return d3.getMonth();
}else if(f == "%Y"){
return d3.getFullYear();
}else{
return '%Y-%m-%d';
}
},
rotate: 75,
}
But I don't know how can I change x-axis date format dynamically. I already try a lot of way but I can't get correct result.
I very appreciate for any suggestion.
Upvotes: 2
Views: 1890
Reputation: 6207
d3 doesn't have getDay() / getMonth() / getFullYear() functions, what you need (if f exists) is
d3.time.format(f)
See https://github.com/mbostock/d3/wiki/Time-Formatting
(Moreover, you're not really changing the formatting dynamically as far as the chart is concerned, you're generating a new c3 chart each time, though that's probably just semantics.)
Upvotes: 1