Passing values to chart.js - Laravel - javascript

I am able to fetch data from database which i want to pass to a chart.js. With the code below,
the chart displays ["{items: Nike}",total:20"},"{items: Addidas}",total:40"}] in the xaxis.
But then i want it to display like
categories: ['Nike', 'Addidas'];
Controller
$items = DB::table('items_tbl')->select('name', DB::raw('count(*) as total'))->groupBy('name')
->get();
return view('home',compact('items'));
HTML
<script>
var items_pass = #json($items)
</script>
JS
xaxis: {
categories: [JSON.stringify(items_pass)],
axisBorder: {
show: true,
color: '#bec7e0',
},
axisTicks: {
show: true,
color: '#bec7e0',
},
},

Related

looker custom visualization using echarts

Am creating custom visualization and am using echarts for the visualization.
I have a source and everything but i am unable to make it work. Can anyone help in this how to achieve the below fiddle in looker custom visualization
import * as echarts from 'echarts';
var ROOT_PATH = 'https://echarts.apache.org/examples';
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
myChart.showLoading();
$.getJSON(ROOT_PATH + '/data/asset/data/les-miserables.json', function (graph) {
myChart.hideLoading();
graph.nodes.forEach(function (node) {
node.label = {
show: node.symbolSize > 30
};
});
option = {
title: {
text: 'Les Miserables',
subtext: 'Default layout',
top: 'bottom',
left: 'right'
},
tooltip: {},
legend: [{
// selectedMode: 'single',
data: graph.categories.map(function (a) {
return a.name;
})
}],
animationDuration: 1500,
animationEasingUpdate: 'quinticInOut',
series: [
{
name: 'Les Miserables',
type: 'graph',
layout: 'none',
data: graph.nodes,
links: graph.links,
categories: graph.categories,
roam: true,
label: {
position: 'right',
formatter: '{b}'
},
lineStyle: {
color: 'source',
curveness: 0.3
},
emphasis: {
focus: 'adjacency',
lineStyle: {
width: 10
}
}
}
]
};
myChart.setOption(option);
});
option && myChart.setOption(option);
demo url
in the above snippet, they are passing json but in my requirement i need to fetch from selected dimensions or measures and I need to convert into looker custom viz
looker.plugins.visualizations.add({
});
Please do let me know any suggestions on this
Inside the object you pass to looker.plugins.visualizations.add, the updateAsync method ( that you will use to generate the echart options and series ) is async, and it passes you a done callback to be called when you are ready.
So you can call your json, process the data and then done()

How to fetch json array data into highcharts in angularjs

I want to display a bar graph using highcharts.I am devoloping an app in play framework(play-java),in which I return a response from the java api which contains data in json format.It contains a field 'name' which contains data like 'Data','Gadgets','Others' etc.I want the x axis of the chart to take these values from json array which gets returned in response.
Here is the code for the response in .js
for(var i=0;i<response.data.result.length;i++)
{
$scope.total=$scope.total+parseInt(response.data.result[i].item_price);
}
var j=0;
console.log(response.data.result);
while(j<response.data.result.length)
{
$scope.jsonArray=[{
name:response.data.result[j].category_name,
y: (parseInt(response.data.result[j].item_price)/$scope.total)*100,
}]
$scope.renderChart();
}
The code for bar graph
$scope.renderChart = function()
{
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Your Expenses'
},
subtitle: {
text: 'Your total spent money is '+$scope.total+'.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Money spent in percentage'
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Categories',
colorByPoint: true,
data:$scope.jsonArray
}]
});
}
I know that I can't use the while loop in the response code mentioned.That's where i am looking help for.The y axis should calculate the percentage value .I want to generate 'names' for x axis and percentage for y axis of the chart.Thanks in advance..
All we have to do is to just initialize the jsonArray as empty before doing the looping.Add a for loop so that it iterates through the array and assigns the values appropriately.
The changed code
$scope.jsonArray = [];
for(var i=0;i<response.data.result.length;i++)
{
$scope.jsonArray[i]={
name:response.data.result[i].category_name,
y: (parseInt(response.data.result[i].item_price)/$scope.total)*100,
}
$scope.renderChart();
console.log(response.data.result[i]);
}
console.log($scope.jsonArray);
})
Anyway thanks....

Different tooltips for series in FlotChart

I have Flot line chart with two dataseries. I would like to edit the tooltips independently for each series. I have tried moving the tooltip settings to the dataset part but it didn't work.
Does anyone know a solution?
$(function () {
var barOptions = {
xaxis: {
tickDecimals: 0
},
yaxes: [{
position: "left"
}, {
position: "right"
}],
colors: ["#36c6d3"],
grid: {
color: "#888888"
},
tooltip: {
show: true,
content: "Uge %x, %s: %y"
}
};
var dataset = [{
data: occData.data,
label: occData.label,
yaxis: occData.yaxis,
lines: {
show: true,
lineWidth: 1,
}
}, {
data: houseData.data,
label: houseData.label,
yaxis: houseData.yaxis,
color: 'grey',
lines: {
show: true,
lineWidth: 1,
fill: false
}
}];
$("#flot-line-chart-past").plot(dataset, barOptions);
});
I'm going to presume that you are using flot.tooltip to provide the tooltips. In which case, the content property of the tooltip configuration object can be a function as well as a format string. I quote from the documentation for the plug-in:
you can pass a callback function(label, xval, yval, flotItem) that must return a string with the format described.
So write a function that distinguishes between each label you use for the two series, and return a different format string for each.

Queried Data as Datapoints on Chart.js

I am trying to plot chart using Chart.JS based on my data from database. Here number of Labels and their values will come directly from the query result. Here is my code:
<script type="text/javascript">
window.onload = function () {
<?php
function getValsOfCategoryLabels(){
$yValsWithLabels = "";
......
// some codes to make query on db and get result in $queryResult variable
......
......
foreach($queryResult as $data){
$x0 = $data0['name'];
$total = $data0['total'];
$yValsWithLabels = $yValsWithLabels. "{y: ".$total.", label: \"".$x0."\"}, ";
}
return $yValsWithLabels;
}
?>
var categoryLabelsNdVals = [<?php echo getValsOfCategoryLabels() ?>];
var hourlyCategoryBarChart = new CanvasJS.Chart("columnchartContainer", {
animationEnabled: true,
axisX: {
labelFontSize: 16
},
axisY: {
title: "",
labelFontSize: 13
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 16
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "Name of Category",
dataPoints: categoryLabelsNdVals
}
]
});
hourlyCategoryBarChart.render();
Now for the given datapoints (which is in "{y: Some_Value, label: Some_Name}" format) I am not getting any chart as output, unless I explicitly declare all the y-axis values and label names myself, which fails reflect database info.
What is the right way to accomplish my objective?

How to implement Highcharts column-drilldown chart in Rails application?

I'm trying to implement a Highcharts Column-Drilldown Chart in my Rails application using lazy_high_charts. I want to display data that's being pulled from my database and stored in four arrays (areas, areaScores, departments, and deptScores). I'm having trouble converting the JS from the example (JSFiddle) listed on the highchart site into ruby. I have not been able to find any resources on creating a column-drilldown chart in ruby. Any help on how to integrate the drilldown chart into my ruby application would be highly appreciated.
I have included the sample JavaScript shown on the Highcharts demo page and my controller method that populates the four arrays with data and builds the highchart.
Highcharts Column-Drilldown Chart Example (Javascript)
$(function () {
Highcharts.data({
csv: document.getElementById('tsv').innerHTML,
itemDelimiter: '\t',
parsed: function (columns) {
var brands = {},
brandsData = [],
versions = {},
drilldownSeries = [];
// Parse percentage strings
columns[1] = $.map(columns[1], function (value) {
if (value.indexOf('%') === value.length - 1) {
value = parseFloat(value);
}
return value;
});
$.each(columns[0], function (i, name) {
var brand,
version;
if (i > 0) {
// Remove special edition notes
name = name.split(' -')[0];
// Split into brand and version
version = name.match(/([0-9]+[\.0-9x]*)/);
if (version) {
version = version[0];
}
brand = name.replace(version, '');
// Create the main data
if (!brands[brand]) {
brands[brand] = columns[1][i];
} else {
brands[brand] += columns[1][i];
}
// Create the version data
if (version !== null) {
if (!versions[brand]) {
versions[brand] = [];
}
versions[brand].push(['v' + version, columns[1][i]]);
}
}
});
$.each(brands, function (name, y) {
brandsData.push({
name: name,
y: y,
drilldown: versions[name] ? name : null
});
});
$.each(versions, function (key, value) {
drilldownSeries.push({
name: key,
id: key,
data: value
});
});
// Create the chart
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Browser market shares. November, 2013'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Brands',
colorByPoint: true,
data: brandsData
}],
drilldown: {
series: drilldownSeries
}
})
}
});
});
My Controller:
def generateOrgBreakdownReport
# First, query the database for the data you need for the report
#jsonanswerBRKD = queryDatabaseForOrgProgressReport()
# Second, process and combine data as needed for the report
#areaBreakdown, #deptBreakdown, #employBreakdown = computeAreaAndDeptPrepareScore(#jsonanswerBRKD)
# Third, you'll need to put the processed data into a format
# Highcharts will understand for the data series it uses
# for the graph.
#THESE ARRAYS HOLD THE NAMES AND SCORES OF AREAS AND DEPARTMENTS
#deptScores, #departments, #areaScores, #areas = cycleThroughProcessedDataAndCreateHighChartsDataSetsBreakdown(#areaBreakdown, #deptBreakdown, #employBreakdown)
# Last, we put the newly made data sets for Highcharts to work its magic.
#DONT KNOW HOW TO IMPLEMENT DRILLDOWN FOR RUBY
#orgBreakdown = LazyHighCharts::HighChart.new('column') do |f|
f.chart( type: 'column' )
f.xAxis(
title: { text: "Areas" },
type: 'category'
)
f.yAxis(
title: { text: "Preparedness Score (%)"},
)
f.series(
name: "Department Score",
colorByPoint: true,
data: #deptScores
)
f.series(
name: "Area Score",
data: #areaScores
)
f.title(
text: "Organizational Breakdown"
)
f.options[:xAxis][:categories] = #areas
f.drilldown({:series=>{
name:"Dept. Score",
data: #deptScore
}
})
end
end
Thanks,
Matt
I haven't used Lazy Highcharts, but assuming it mirrors the JSON from the JavaScript API you need to add the sub-series by name, e.g.
f.series(
name: "Department Score",
colorByPoint: true,
data: #deptScores,
drilldown: "subdept" #add this
)
Then you'll need to add drilldown data, and if Lazy Highcharts supports it, it might look something like this:
f.drilldown(
series: {
id: "subdept",
data: [
["One", 1],
["Two", 2],
["Three", 3]
]
}
)
See this basic drilldown fiddle to see how the resulting Javascript should look.
To get drilldown to work in Rails you have to make sure you include the drilldown module in your JavaScript manifest file (application.js).
I also had to download the file as it was not my highcharts module catalogue. You can find the file here: http://code.highcharts.com/modules/drilldown.js
Add this to application.js:
//= require highcharts/modules/drilldown
Outside of Rails you can include the drilldown module like this:
<script src="http://code.highcharts.com/modules/drilldown.js"></script>

Categories

Resources