Trouble showing results with pie highchart - javascript
I'm totally new to Highcharts and I made two types of them: spline and pie. They now look like this:
And this:
The problem I have can be seen immediately. Since I have two buttons on which user can determine how he wants his chart to appear:
I succeed to update chart type like so:
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
});
}
});
But I don't want this pie chart to appear like this. I want, like in spline type that values represent each day, not Notiflow:35 etc. This is code responsible for charts:
var type='';
$('#spline').click(function(){
if($('#spline').hasClass('active')!=true){
$('#pie').removeClass('active');
$('#spline').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "spline"
});
}
});
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
});
}
});
$(function () {
if($('#spline').hasClass('active')){
type='spline';
}else{
type='pie';
}
$('#curve_chart').highcharts({
chart: {
type: type
},
title: {
text: 'Click through rate:'
},
xAxis: {
categories: [<?php foreach ($percentagePerDay as $key => $value) {
if ($value != $last) {
echo substr($key, -2);
echo ',';
} else {
echo substr($key, -2);
}
}?>]//key
},
yAxis: {
title: {
text: 'Percentage'
}
},
series: [{
name: '<?= $name ?>',
data: [<?php foreach ($percentagePerDay as $key => $value) {
if ($value != $last) {
echo $value;
echo ',';
} else {
echo $value;
}
}?>]//value
}]
});
});
I tried to make pie chart to represent hard coded values like so:
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
series:[{
data:[['11',35],['12',15],['13',30],['14',20]]
}]
});
}
});
}
});
But pie highchart didn't changed. What more do I need to add to this line(except of type):
$('#curve_chart').highcharts().series[0].update({});
in order for my pie to represent values for each day within range like spline does and to remove those 'slice' moments?
UPDATE:
So, this is how I want my pie to look:
When updating series o not pass series in object - only series properties, like name, type, data, etc. To have dataLabels like in the image you only will need to set names for points, Highcharts will make it work.
Example: http://jsfiddle.net/tvd6faf9/
Related
How to add a second series in highcharts [duplicate]
This question already has an answer here: Retrieving JSON data for Highcharts with multiple series? (1 answer) Closed 2 years ago. I have been trying to display the second value of my json file in highcharts for two days. my json file: [[1591518187000,17.3,12.7],[1591518135000,17.2,12.7]...[1591518074000,17.2,12.6],[1591518020000,17.2,12.7]] The time and the first value are displayed correctly. my script in php file: <script type="text/javascript"> var chart; function requestData() { $.getJSON('../****json.php', function (data) { var series = chart.series[0]; series.setData(data); } ); } (document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: 'container', defaultSeriesType: 'line', marginRight: 10, marginBottom: 25, events: { load: requestData } }, ..... series: [{ name: 'Temperatur', data: [] }, { name: "Taupunkt", data: [] ...... </script> Does anyone happen to have a way of drawing the second values as a line?
You could process your data and make two data sets for both series. Both data sets will have the same x values, but different y values. The code could look something like this: $.getJSON('../****json.php', function (data) { var dataSetOne = [], dataSetTwo = []; data.forEach(function(point) { dataSetOne.push([point[0], point[1]); dataSetTwo.push([point[0], point[2]); }); chart.series[0].setData(dataSetOne); chart.series[1].setData(dataSetTwo); } );
highchart use ajax to php+mysql
I use highchart on the leaflet map. I use ajax to grab the data in php. I can see the data returned in console.log, but I can't draw a line chart. Is there any problem? I directly write php,js and html in a program code can be displayed, the data format I have not changed. This is my result This is console.log show This is my html code: <div class="inner"> <div id="map" style="width: 600px; height: 400px;"></div> <script src="assets/js/leaflet2.js"></script> </div> leaflet2.js function onClick(e){ var popup = e.target.getPopup(); var content = popup.getContent(); var find_1 = content.indexOf('>'); var find_2 = content.indexOf('/'); var id = content.substring(find_1+1,find_2-1); $.ajax({ type: 'POST', url: 'http://localhost/html5up-helios/chart.php', data: { "device":id }, success:function(data){ // console.log(data); var modify = data.indexOf('['); var show = data.substring(modify); console.log(show); var chart = new Highcharts.Chart({ chart: { height: 175, width: 300 , renderTo: 'container'}, title: { text: '' }, series: [{ name: 'PM 2.5', data: show } ], credits: { enabled: false }, exporting:{ enabled:false } }); } }); } chart.php <?php include("connection.php"); if (isset($_POST["device"])) { $id = $_POST["device"]; error_log(print_r($id, true)); } else { error_log(print_r("error", true)); } try { $sql = "SELECT * FROM day WHERE DATE_SUB(curdate(), INTERVAL 20 DAY) <= date(date)"; if ($stmt = $db->query($sql)) { while ($result = mysqli_fetch_array($stmt)) { $number_pm = intval($result['pm25']); if ($number_pm < 0) { $number_pm = 0; } $pm25[] = array( $result['date'], $number_pm ); } $pm25 = json_encode($pm25); echo $pm25; } } catch (Exception $e) { die($e); } ?> In addition to this, isset ($ _ POST ["device"]) in my php will display an error, but I have to pass the data out in leaflet.js( $ .ajax ({ type: 'POST', url: 'http: //localhost/html5up-helios/chart.php', data: { "device": id },}); ) php doesn't seem to receive anything, or am I wrong?
Google Chart: "c.getTimezoneOffset is not a function" error
I'm trying to display a line chart of currency rates via google charts. Basically i have 2 type of values: Date (format iso8601) Rate (decimal number) When i try to render the chart with Date as type string, it renders nicely. But when i try to render the chart with Date as type date/datetime, i get the following error: "c.getTimezoneOffset is not a function" Here is my code: PHP array making: $arrayForChart =array(); foreach ($arrayRates as $key => $value) { $dateObj= new datetime($value['date']);//$value['date']= date in iso 8601 format: e.g 2017-02-12 $dateStringNewDate="new Date(" . $dateObj->format('Y') .",". $dateObj->format('m') . "," . $dateObj->format('d') . ")";//temp for testing $dateStringDate="Date(". $value['date'] . ")";//temp for testing array_unshift($arrayForChart, array($dateStringDate , $value['rates']["$toCurrency"])); } array_unshift($arrayForChart, array(array('label'=>'Date','id'=>'Date','type'=>'date'),array('label'=>'Rate','id'=>'Rate','type'=>'number'))); Javascript function dipsplayChart() { //from here google chart stuff google.charts.load("current", { packages: ["corechart", "line"] }); google.charts.setOnLoadCallback(drawLineColors); function drawLineColors() { console.log(JSON.stringify(arrayForChart)); var data = google.visualization.arrayToDataTable(arrayForChart); var options = { title: baseCurrency + " vs " + toCurrency + " Last 90 days", explorer: { actions: ["dragToZoom", "rightClickToReset"], axis: "horizontal", keepInBounds: true }, hAxis: { title: "Date" //type: "date" }, vAxis: { title: "Rate" //type: "number" }, colors: ["#a52714", "#097138"] }; var chart = new google.visualization.LineChart( document.getElementById("chart_div") ); chart.draw(data, options); } //until here google chart stuff } Data example: [[{"label":"Date","id":"Date","type":"date"},{"label":"Rate","id":"Rate","type":"number"}],["new Date(2017,04,10)",3.6618],["new Date(2017,04,11)",3.6565],["new Date(2017,04,12)",3.6551],["new Date(2017,04,13)",3.6539],["new Date(2017,04,18)",3.6652],["new Date(2017,04,19)",3.6655],["new Date(2017,04,20)",3.6651],["new Date(2017,04,21)",3.6798],["new Date(2017,04,24)",3.6523],["new Date(2017,04,25)",3.6443],["new Date(2017,04,26)",3.6365],["new Date(2017,04,27)",3.644],["new Date(2017,04,28)",3.622],["new Date(2017,05,02)",3.6094],["new Date(2017,05,03)",3.6171],["new Date(2017,05,04)",3.6191],["new Date(2017,05,05)",3.6038],["new Date(2017,05,08)",3.6049],["new Date(2017,05,09)",3.6034],["new Date(2017,05,10)",3.6007],["new Date(2017,05,11)",3.6114],["new Date(2017,05,12)",3.6045],["new Date(2017,05,15)",3.597],["new Date(2017,05,16)",3.6056],["new Date(2017,05,17)",3.6017],["new Date(2017,05,18)",3.6045],["new Date(2017,05,19)",3.5859],["new Date(2017,05,22)",3.5817],["new Date(2017,05,23)",3.5871],["new Date(2017,05,24)",3.5897],["new Date(2017,05,25)",3.5769],["new Date(2017,05,26)",3.5734],["new Date(2017,05,29)",3.5724],["new Date(2017,05,30)",3.5517],["new Date(2017,05,31)",3.5431],["new Date(2017,06,01)",3.5511],["new Date(2017,06,02)",3.5605],["new Date(2017,06,05)",3.549],["new Date(2017,06,06)",3.5461],["new Date(2017,06,07)",3.5457],["new Date(2017,06,08)",3.5358],["new Date(2017,06,09)",3.5242],["new Date(2017,06,12)",3.533],["new Date(2017,06,13)",3.5258],["new Date(2017,06,14)",3.5295],["new Date(2017,06,15)",3.5225],["new Date(2017,06,16)",3.5274],["new Date(2017,06,19)",3.5225],["new Date(2017,06,20)",3.5391],["new Date(2017,06,21)",3.5409],["new Date(2017,06,22)",3.5441],["new Date(2017,06,23)",3.5418],["new Date(2017,06,26)",3.531],["new Date(2017,06,27)",3.5168],["new Date(2017,06,28)",3.52],["new Date(2017,06,29)",3.4955],["new Date(2017,06,30)",3.4953],["new Date(2017,07,03)",3.4979],["new Date(2017,07,04)",3.516],["new Date(2017,07,05)",3.5195],["new Date(2017,07,06)",3.5361]] Anybody know what is the problem? Many thanks!!
ChartJS + twig symfony
I've got an issue, I'm trying to create a chart (pie) with ChartJS using twig data. The chart label uses an array, so I'm giving a twig array to it like this : var myChart = new Chart(ctx, { type: 'pie', data: { labels: ({{array|json_encode()|raw}}) But it displays "object Object". For my purpose I want to display an attribute of that object, in that example : "intitule" Thanks a lot.
I suggest you write an own Twig extension and add a filter function to it: 1. Create the extension class and add a filter with name chart: // src/AppBundle/Twig/AppExtension.php namespace AppBundle\Twig; class AppExtension extends \Twig_Extension { public function getFilters() { return array( new \Twig_SimpleFilter('chart', array($this, 'chartFilter')), ); } public function chartFilter($items, $key = 'intitule') { $output = []; foreach ($items as $item { if (array_key_exists($key, $item)) { $output[] = $item[$key]; } } return json_encode($output)); } } 2. Create service Depending on your services.yml definition you may need to create a service for the extension: app.twig_extension: class: AppBundle\Twig\AppExtension tags: - { name: twig.extension } 3. Use the filter in your view you can use the filter using it like this: var myChart = new Chart(ctx, { type: 'pie', data: { labels: ({{array|chart|raw}})
How to add {text} (without quotes) to an array in PHP for Google Chart API?
Updated following Uberfuzzy advice: $a = '{"role": "tooltip","p": {"html": true}}'; $aa = json_decode($a,true); $data[0] = array_merge(array(product),$info,array($aa)); This thread shows how to customize the html content of the tooltip in Google Chart API using arrayToDataTable. It requires the format like this: [ ['Country', 'Value', {role: 'tooltip', p:{html:true}}], ['Russia', 5, 'Hello world<br>test'], ['US', 20, '<img src="logo6w.png"/>'] ] Fiddle Example. I was using AJAX to generate a JSON output from mysql and pass into arrayToDataTable function. The code below gives me this output: [["product","diameter","width"],["Product 1",2,4],["Product 2",4,8]] $_POST["info"] Content: Array ( [0] => diameter [1] => width ) PHP Code: $rows = $users->fetchAll(); $data=""; $data[0] = array_merge(array(product),$info); $i = 1; foreach ($rows as $row) { $d[]=$row["name"]; foreach($_POST["info"] as $p) { $d[]= $row[$p]; } $data[$i] = $d; $d=array(); //set $d to empty not to get duplicate results $i++; } echo json_encode($data,JSON_NUMERIC_CHECK); How can I insert {role: 'tooltip', p:{html:true}} in $data[0]? It isn't an array, so I can't simply use $data[0] = array_merge(array(product),$info,array({role: 'tooltip', p:{html:true}})); jQuery: function drawChart() { var info = $('input:checked').map(function(){ return $(this).val() }).get(); var tt = $('.tt').map(function(){ return $(this).data('tid') }).get(); console.log(tid); var title = $('h3').text() var jsonData = $.ajax({ url: "test.php", type:"POST", dataType: "json", data:{'info[]':info,'tt':tt}, async: false }).responseText; var data = google.visualization.arrayToDataTable($.parseJSON(jsonData)); var options = { tooltip: {isHtml: true}, hAxis: { textStyle: {fontSize: 11}, slantedText: true, slantedTextAngle: 40 } }; var chart = new google.visualization.LineChart( document.getElementById('chart')); chart.draw(data, options); }
It looks like your {role: 'tooltip', p:{html:true}} is json, so run json_decode (remember to pass true as the 2nd param) on it to get a php native array, THEN do your array merging.
json_encode converts PHP's associative arrays to javascript objects, so to create {role: 'tooltip', p:{html:true}}, you would create a PHP array like this: $jsObj = array( 'role' => 'tooltip', 'p' => array( 'html' => true ) );