For my project i want to use the json file below to show in the highcharts.
For some reason the chart stays empty.
i think i need to format the json part in someway but i cant seem the figure out how.
Im pretty new to this, so I hope someone can explain the code to me in a simple way.
how do i format the code below? I want to use the colum chart.
[
{
"stadsdeel":"A Centrum",
"veiligheid":18994,
"leefbaarheid":3822,
"maatschappelijke integriteit":733,
"totaal":23549
},
{
"stadsdeel":"B Westpoort",
"veiligheid":878,
"leefbaarheid":318,
"maatschappelijke integriteit":88,
"totaal":1284
},
{
"stadsdeel":"E West",
"veiligheid":8648,
"leefbaarheid":1672,
"maatschappelijke integriteit":536,
"totaal":10856
},
{
"stadsdeel":"F Nieuw-West",
"veiligheid":8673,
"leefbaarheid":1832,
"maatschappelijke integriteit":690,
"totaal":11195
},
{
"stadsdeel":"K Zuid",
"veiligheid":10065,
"leefbaarheid":2171,
"maatschappelijke integriteit":767,
"totaal":13003
},
{
"stadsdeel":"M Oost",
"veiligheid":8284,
"leefbaarheid":1576,
"maatschappelijke integriteit":511,
"totaal":10371
},
{
"stadsdeel":"N Noord",
"veiligheid":5011,
"leefbaarheid":1324,
"maatschappelijke integriteit":385,
"totaal":6720
},
{
"stadsdeel":"T Zuidoost",
"veiligheid":5031,
"leefbaarheid":1264,
"maatschappelijke integriteit":677,
"totaal":6972
},
{
"stadsdeel":"X onbekend",
"veiligheid":196,
"leefbaarheid":46,
"maatschappelijke integriteit":26,
"totaal":268
},
{
"stadsdeel":"Amsterdam",
"veiligheid":65780,
"leefbaarheid":14025,
"maatschappelijke integriteit":4413,
"totaal":84218
}
]
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('charts.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
Each point need to have y paramter with number value, becasuse highcharts use this param to calculate position of point.
Related
I am not a JavaScript expert and I am trying to put a simple pie chart together using the data from a csv file. The sample code for the pie chart with its input data looks like below and it works perfectly.
var pie = new d3pie("pie", {
header: {
title: {
text: "A Very Simple Pie",
fontSize: 30
}
},
data: {
content: [
{ label: "JavaScript", value: 264131 },
{ label: "Ruby", value: 218812 },
{ label: "Java", value: 157618}
]
}
});
but when I try to use the data from the csv file. It says no data is provided. I obviously try to pass the dynamic data to the data.content but it seems like I am not doing it correctly. Below is my code:
var input_data = []
d3.csv("data.csv", function (data) {
input_data.push({
label: data["First"],
value: +data["Age"]
});
});
console.log(input_data); // This shows [{label: "james", value:30},{"John",value:22}]
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
Any idea what I am doing wrong here?
As noted in my comment, your problem is because d3.csv acts asynchronously, and input_data isn't populated when d3pie tries to create your chart.
There is something highly suspicious going on with input_data in the other examples -- it should be called for every item in data, but seems only to be called once. Rather than using input_data to collate intermediate results, it's much easier to use javascript's map function to transform your csv data into the format you want:
d3.csv("data.csv", function (data) {
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: data.map( function(d){
return { label: d['First'], value: +d['Age'] }
})
}
});
});
map iterates over an array and produces an array as output, so it's much cleaner and easier than creating extra arrays on to which you push data, etc.
You probably want to put your d3pie code inside your callback function because you want to call it after the data returns (see this example):
var input_data = []
d3.csv("data.csv", function (data) {
input_data.push({
label: data["First"],
value: +data["Age"]
});
console.log(input_data); // This shows [{label: "james", value:30},{"John",value:22}]
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
});
const promise = d3.csv("data.csv", function (data) {
input_data.push({
'label': data["First"],
'value': +data["Age"]
});
});
promise.then(function(){
var pie = new d3pie("pieChart", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
});
I´m developing a visualization module for some crypto portfolios with vue.js and chart.js but am currently stuck with this:
Empty chart is displayed but non of the values are rendered.
Since the values are dynamically loaded after the chart is initialized I believe that the chart is not updating itself properly (even though I call .update()), but no errors are displayed whatsoever.
I wrapped the chart.js rendering in a vue component:
Vue.component('portfolioValues', {
template: '<canvas width="400" height="200"></canvas>',
data: function() {
return {
portfolio_value: [],
portfolio_labels: [],
chart: null,
}
},
methods: {
load_portfolio_value_local: function() {
values = [];
labels = []
local_data.forEach(element => {
values.push(element.total_usd);
labels.push(moment(element.timestamp, 'X'));
});
this.portfolio_value = values;
this.portfolio_labels = labels;
this.chart.update();
},
render_chart: function() {
this.chart = new Chart(this.$el, {
type: 'line',
data: {
labels: this.portfolio_labels,
datasets: [{
label: "Portfolio Value",
data: this.portfolio_value,
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
}]
}
}
});
}
},
mounted: function() {
this.render_chart();
this.load_portfolio_value_local();
}
});
For demonstration purposes I just added some data locally, looks like this:
local_data = [{
"timestamp": 1515102737,
"total_btc": 0.102627448096786,
"total_usd": 1539.41274772627
}, {
"timestamp": 1515102871,
"total_btc": 0.102636926127186,
"total_usd": 1538.52649627725
}, {
"timestamp": 1515103588,
"total_btc": 0.102627448096786,
"total_usd": 1532.33042753311
}
]
Here is the full demo code: https://codepen.io/perelin/pen/mppbxV
Any ideas why no data gets rendered? thx!
The problem you have here is how vuejs handles its data.
If you use it like that:
local_data.forEach(element => {
this.portfolio_value.push(element.total_usd);
this.portfolio_labels.push(moment(element.timestamp, 'X'));
});
this.chart.update();
The chart will update. But by re-initializing the arrays you work against vuejs.
TL;DR
If you want to re-initialize an object, you could assign the array to the object:
Object.assign(this.portfolio_value, values);
Object.assign(this.portfolio_labels, labels);
That way, the linking stays working.
How can I set the y lines value to the first value from URL? (JSON data)
var chartDisplay = c3.generate({
bindto: '.chart',
data: {
url: '/stats',
mimeType: 'json',
},
grid: {
y: {
lines: [ {
value: data1 <---- this is what I cant figure out
}
]
}
}
});
The json data looks like this:
{
"data1": 3000,
"data2": [
3000,
3300.0,
3410.0,
4520.0,
]
}
try adding this to your chart declaration,
onrendered: function () {
this.api.ygrids([
{value: this.data.targets[0].values[0].value, text:'data 1 value'},
]);
},
this.api is basically the same as the 'chart' variable, and this.data is a pointer to the loaded dataset. targets[0] will be the first series loaded (data1) and values[0].value will be the value of the first entry
http://jsfiddle.net/y7axwubf/1/
What I need:
when charts are loaded data is loaded in charts.
Problem I'm facing: Charts are loading but data is not loading.
I'm using sencha docs as Reference Guide.
I just want load data in charts link: http://postimg.org/image/ydbac2soh/
This is the output link that I'm getting url: http://postimg.org/image/5whlpe6wj/
This is code of line charts:
Ext.require('Ext.chart.*');
Ext.require(['Ext.layout.container.Fit', 'Ext.window.MessageBox']);
Ext.define('Employee',{
extend:'Ext.data.Model',
fields:['name','yearOfExperience']
});
var store=Ext.create('Ext.data.Store',{
model:'Employee',
data:[
{ name:'sam', yearOfExperience:12 },
{ name:'ram', yearOfExperience:7 },
{ name:'kim', yearOfExperience:16 },
{ name:'john', yearOfExperience:21 },
{ name:'Mary', yearOfExperience:13 }
]
});
Ext.onReady(function () {
Ext.Msg.alert("hello","all set");
Ext.create('Ext.chart.Chart',
{
width:500,
height:300,
animate:true,
shadow:store,
store:store,
renderTo:Ext.getBody(),
legend: {
position:'right'
},
insertPadding:25,
theme:'Base:gradients',
axes:[
{
title:'years Of Experience',
type:'Numeric',
position:'left',
fields:['yearOfExperience'],
minimum:0,
maximum:30
},
{
title: 'Employee',
type: 'Category',
position:'bottom',
fields:['name']
}
],
series:[
{
type:"line",
xFields: "name",
yField :"yearOfExerince"
}
]
});
});
I have used dummy data t load in charts in ext js.
Charts are loaded perfectly but data is not loaded in charts please help where i have done wrong.
I have tried with dummy data in charts but no data is loading.
Here is the output link: http://postimg.org/image/5whlpe6wj/.
Try setting the store to:
autoLoad = true;
I have started using Typeahead.js and am struggling to figure out a way of allowing a user to type and search for a company name, once selected input the associated company code.
.json file:
[{
"company_name": "Facebook",
"code": "fb",
}, {
"company_name": "Google",
"code": "goog",
}, {
"company_name": "Yahoo",
"code": "yhoo",
}, {
"company_name": "Apple",
"code": "aapl",
}, {
"company_name": "Royal Mail",
"code": "rmg.l",
}]
.js Script:
var stocks = new Bloodhound({
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.code);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 3,
prefetch: {
url: 'javascripts/stockCodes.json',
filter: function(list) {
return $.map(list, function(stock) {
return {
code: stock
};
});
}
}
});
stocks.initialize();
$('.typeahead').typeahead(null, {
name: 'stocks',
displayKey: 'code',
source: stocks.ttAdapter()
});
Currently, this just displays the list of codes when the user types in the input field. However, I would like to know if there is a way to allow them to search on code but once selected, the value in the textbox to be company_name? Is this even possible using this plugin. Any help will be greatly appreciated.
Thanks!
displayKey is used to indicate which key should be shown in the dropdown list and in the input field after the user has selected an entry.
If you want the entries shown in the dropdown list to be different from what ends up in the input field you need to use a custom template.
From the documentation:
suggestion – Used to render a single suggestion. If set, this has to be a
precompiled template. The associated suggestion object will serve as the
context. Defaults to the value of displayKey wrapped in a p tag i.e.
<p>{{value}}</p>.
Something like this should work:
$('.typeahead').typeahead(null, {
name: 'stocks',
displayKey: 'company_name',
source: stocks.ttAdapter(),
templates: {
suggestion: function (stock) {
return '<p>' + stock.code + '</p>';
}
}
});
The submitted template will be used to show stock.code in the dropdown list, while stock.company_name will be shown in the input field after the user selects an entry.
I am no jQuery / JavaScript-Guru. So I prefer it the easy way. Just to understand what I did when I look at my code later...
Thanks to Eric Saupe I found a smart solution:
//JSON FILE
[
{
"company_name": "Facebook",
"code": "fb",
},
{
"company_name": "Google",
"code": "goog",
},
{
"company_name": "Yahoo",
"code": "yhoo",
},
{
"company_name": "Apple",
"code": "aapl",
},
{
"company_name": "Royal Mail",
"code": "rmg.l",
},
]
// JS SCRIPT
var stocks = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('company_name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: 'javascripts/stockCodes.json'
});
stocks.initialize();
$('.typeahead').typeahead(
null, {
name: 'stocks',
displayKey: 'company_name',
source: stocks.ttAdapter()
}).on('typeahead:selected', function(event, data){
$('.typeahead').val(data.code);
});
Just use the typeahead custom events as described in the docs on github.
Hope, this helps (and when it's just for my own later reference).
JSFIDDLE
You need to use the ´displayKey´ variable. See below copy-paste from the typeahead docs:
displayKey – For a given suggestion object, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. Defaults to value.
https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md
Your specific code would then be something like this:
var stocks = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.code); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 3,
prefetch: {
url: 'javascripts/stockCodes.json',
filter: function(list) {
// This should not be required, but I have left it incase you still need some sort of filtering on your server response
return $.map(list, function(stock) { return { code: stock.code, company_name: stock.company_name }; });
}
}
});
stocks.initialize();
$('.typeahead').typeahead(null, {
name: 'stocks',
displayKey: function(stock) {
return stock.company_name;
},
source: stocks.ttAdapter()
});
I had a very similar requirement on my own site, and I had this working with no issue. I have not tried this particular example though, so let me know if it works.
Remember to call stocks.clearPrefetchCache(); to clear your cache to easier track bugs.
If I read correctly, I believe this is what you want:
var stocksData = [{
"Facebook": "fb",
}, {
"Google": "goog",
}, {
"Yahoo": "yhoo",
}, {
"Apple": "aapl",
}, {
"Royal Mail": "rmg.l",
}, ];
var stocks = new Bloodhound({
datumTokenizer: function (d) {
for (var prop in d) {
return Bloodhound.tokenizers.whitespace(d[prop]);
}
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 3,
local: stocksData,
});
stocks.initialize();
$('input').typeahead(null, {
name: 'stocks',
displayKey: function(stocks) {
for (var prop in stocks) {
return prop;
}
},
source: stocks.ttAdapter()
});
You will of course want to change the local to prefetch/remote like you had for the json file.
UPDATE
FIDDLE
Had the same problem, could not get it working with the display or displayKey property. Worked around it by adding the name property to the source objects:
$.each(stocks, function (i, item) {
item.name = item.company_name;
});
Add the value that need to be shown in the display parameter:
$(".comp-search").typeahead({
hint: true,
highlight: true,
minLength: 1,
displayKey: 'company_name',
}, {
source: engine.ttAdapter(),
templates: {
empty: ['<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'],
header: ['<div class="list-group search-results-dropdown">'],
suggestion: function (data) {
return '' + data.company_name + '';
}
},
display: function(data) { return data.company_name; }
});
Hope this is helpful