I'm working on a project in Django, for part of it I'm trying to use Googles chart api, which uses a Javascript function to plot the graph. So what I'm trying to do is generate the graph data in my views.py and then pass the data through the context variables to the script. To test this I tried to do:
graphplot = [['Age', 'Weight'],[ 8, 12],[ 4, 5.5],[ 11, 14],[ 4, 5],[ 3, 3.5],[ 6.5, 7]]
context = {
"graphplot": graphplot,
}
in my views.py then I have:
var data = google.visualization.arrayToDataTable({{graphplot}});
in my template, however this doesn't seem to work.
When I do:
var data = google.visualization.arrayToDataTable([
['Age', 'Weight'],
[ 8, 12],
[ 4, 5.5],
[ 11, 14],
[ 4, 5],
[ 3, 3.5],
[ 6.5, 7]
]);
It does show the graph so I know it's not a problem with the JavaScript.
Any help would be appreciated
Try this, It should work.
var plot_data = {{graphplot}};
var data = google.visualization.arrayToDataTable(plot_data);
Related
I saved the json file in python like this
with io.open('tokenizer.json', 'w', encoding='UTF-8') as f:
f.write(json.dumps(tokenizer_json, ensure_ascii=False))
Then when I try to open the file in javascript, the json is read as a raw file
const js = JSON.parse(mytokenizer);
//this does not work properly
//result = {"\uc544\ub2c8\ub2e4": 1, "\uc788\ub2e4": 2, "\uac00\ub2a5\ud558\ub2e4": 3, "\uc5c6\ub2e4": 4, "\ub9c8\uc2a4\ud06c": 5, "\ud55c\ub2e4": 6, "\uc815\ubd80\uac00": 7, "\ub3c5\uac10": 8, "\ubc31\uc2e0\uc758": 9, "\uc54a\ub2e4": 10, "\uad00\uacc4\uac00": 11,
However it works fine when I open this file in python
with open('tokenizer.json') as f:
data = json.load(f)
loaded_tokenizer = tokenizer_from_json(data)
//works fine
//result = {'아니다': 1, '있다': 2, '가능하다': 3, '없다': 4, '마스크': 5, '한다': 6, '정부가': 7, '독감': 8, '백신의': 9, '않다': 10, '관계가': 11, '마스크를': 12,
what is the matter?
you need to set encoding when you open the file:
reader.readAsText(file, 'CP936');
I am using a url to fetch data that constantly updates and changes. It comes back in the form of an array like this:
[[0,14],[1,11],[2,15],[3,12],[4,8],[5,8],[6,9],[7,9],[8,9],[9,7]].
I would like this to be transformed so I can use it in a chart.js
I think I should convert it to a json file, but don't really know how it works because the fetch needs to be initialized every 5 seconds and that new data has to be put in the json file every time and then displayed in the chart.js.
I got the data in the updatingArray[], but i'm stuck now.
function getDataFromDatapointsUrl(){
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = 'https://canvasjs.com/services/data/datapoints.php)';
fetch(proxyurl + url)
.then(response => response.text())
.then(contents => createArrayForUpdatingData(contents));
}
getDataFromDatapointsUrl();
// setInterval(getDataFromDatapointsUrl, 500);
var updatingDataArray = [];
function createArrayForUpdatingData(updatingData){
updatingDataArray.push(updatingData);
}
I would like the data from the array to be split up in the chart.
[[0,14],[1,11],[2,15],[3,12],[4,8],[5,8],[6,9],[7,9],[8,9],[9,7]].
So the 0,1,2,3,4,5,6,... should become the x-axis and the 14,11,15, ... should become the value of the chart-line, bar-, pie, whatever you like it to visualized like.
Based on your example you can simply iterate updatingDataArray and push each value to a separate array that you then pass to Chart.js:
var updatingDataArray = [
[0, 14],
[1, 11],
[2, 15],
[3, 12],
[4, 8],
[5, 8],
[6, 9],
[7, 9],
[8, 9],
[9, 7]
];
var labels = [],
values = [];
updatingDataArray.forEach(function(val, idx) {
labels.push(val[0]);
values.push(val[1]);
});
new Chart(document.getElementById("chart"), {
type: "line",
data: {
labels: labels,
datasets: [{
data: values
}]
},
options: {}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="chart"></canvas>
I am trying to generate multiple c3 charts with the following code :
var datas=[[
["name", "position", "y", "bigRect", "myBars"],
["One 22", 2, 2, 2, 2],
["One 33", 3, 3, 2, 2],
["One 44", 4, 4, 2, 2]
],[
["name", "position", "y", "bigRect", "myBars"],
["Two 55", 5, 5, 2, 2],
["Two 66", 6, 6, 2, 2],
["Two 77", 7, 7, 2, 2]
],[
["name", "position", "y", "bigRect", "myBars"],
["Three 88", 8, 8, 2, 2],
["Three 99", 9, 9, 2, 2],
["Three 00", 0, 0, 2, 2]
]];
var iData = 0;
var charts = [];
for(iData in datas){
var d = datas[iData];
document.querySelector(".container").innerHTML += "<div id='chart"+iData+"'></div>";
var chartSelector = "#chart"+iData;
charts[iData] = c3.generate({
bindto: d3.select(chartSelector),
data: {
rows: d,
type: "scatter",
types: {
bigRect: "area",
myBars: "bar"
},
x: "position",
y: "y"
},
zoom: {
enabled: true
}
});
}
All the charts look empty except the last one that works perfectly. You can see what it looks like on this JSbin link.
On the hidden charts, all the SVGs are generated, but
the g SVG elements that contain the path drawing the dots and bars are set on opacity: 0, hiding all their contents.
the zoom and the tooltip do not work either
Do you know why c3 is disabling the first charts and how to enable them ?
My apologies for my poor English and thank you very much for your time.
You've got it working now, but I can also get it working by replacing one line like so:
d3.select(".container").append("div").attr("id", "chart"+iData);
//document.querySelector(".container").innerHTML += "<div id='chart"+iData+"'></div>";
It appears adding stuff to and then replacing .innerHtml has side effects for the existing contents, in your case the first charts you build
Is it possible to append to innerHTML without destroying descendants' event listeners?
This includes wiping out event handlers and 'unofficial' (for want of a better term) attributes like the __data__ field d3 populates and uses (it's undefined for the first 2 sets of bars as this code will reveal)
for(iData in datas){
console.log (d3.select("#chart"+iData+" .c3-bars").node().__data__);
}
I finally solved my problem by creating all the #chartX containers in another loop before that calling c3.
I assume it has something to do with the non-procedural execution order of JS but I'm still looking for a precise explanation of the phenomenon.
Here is the link to the corrected JSbin.
I am trying to pass code from my PHP backend to the google-chart JavaScript API. I have had success using PHP’s json_encode(), for passing arrays of numbers and strings.
For simple data arrays json_encode() works just fine:
<?php $data = [['Series1', 'Series2'], [0, 1], [2, 3], [3, 4]]; />
<script>
var data = <?php echo(json_encode($data));?>;
</script>
But, the Google Charts API requires that row-parameters be passed as objects in {curly braces}.
Here is the JavaScript array I am trying to produce:
var data = [
['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General',
'Western', 'Literature', { role: 'annotation' } ],
['2010', 10, 24, 20, 32, 18, 5, ''],
['2020', 16, 22, 23, 30, 16, 9, ''],
['2030', 28, 19, 29, 30, 12, 13, '']
];
The trouble is producing the {role: 'annotation'} bit in PHP. Any suggestions?
This should do the trick:
$data = [['Series1', 'Series2', ['role'=>'annotation']], [0, 1], [2, 3], [3, 4]];
You can create objects in php by creating a new stdClass, but an dictionary (key => value array) is converted to JSON the same way (with curly brackets). This would work as well:
$object = new stdClass();
$object->role = 'annotation';
$data = [['Series1', 'Series2', $object], [0, 1], [2, 3], [3, 4]];
You can create an object in PHP and json_encode will create an object from that:
$myObj = new stdClass;
$myObj->role = "annotation";
Then 'json_encode($myObj);' will return the JSON object you want.
consider the example shown in the link Labeling the axis with alphanumeric characters. Is this the correct way to parse var data?
var data = []
d3.csv("data.csv", function(data) {
data = data.forEach(function(d) { return [ x[d[0]], y[d[1]]] });
console.log(data)
});
data.csv should hold these values
[2, 2],
[3, 3],
[4, 4],
[5, 4],
[5.5, 5],
[6, 6],
[6, 7],
[6.5, 8],
[6.5, 16],
[17, 16]
Assuming that you meant that data should hold those values, your data.csv should look like the following:
first,second
2,2
3,3
4,4
5,4
5.5,5
6,6
6,7
6.5,8
6.5,16
17,16
And then you can parse it using the names of the fields:
var data = []
d3.csv("data.csv", function(csvData) {
// By default, all the values read are treated as strings.
// So have to make them numbers explicitly
data = csvData.forEach(function(d) { return [ +d.first, +d.second ] });
console.log(data);
// Draw the chart here.
});