Converting JSON file to GEXF file - javascript

Is there anyway to convert JSON file to GEXF file?
I'm currently using this echarts circular layout graph (https://echarts.apache.org/examples/en/editor.html?c=graph-circular-layout).
However, the JSON file has to be converted to GEXF file format for it to be used in the graph.
Note: My codes are in Javascript.
Thank you!
Updated with codes
Below is the sample codes of using the circular layout graph. It's getting the data from gexf file. However my input data for the graph is in JSON file.
myChart.showLoading();
$.get(ROOT_PATH + '/data/asset/data/les-miserables.gexf', function (xml) {
myChart.hideLoading();
var graph = echarts.dataTool.gexf.parse(xml);
var categories = [];
for (var i = 0; i < 9; i++) {
categories[i] = {
name: '类目' + i
};
}
graph.nodes.forEach(function (node) {
node.itemStyle = null;
node.value = node.symbolSize;
node.symbolSize /= 1.5;
node.label = {
normal: {
show: node.symbolSize > 10
}
};
node.category = node.attributes.modularity_class;
});
option = {
title: {
text: 'Les Miserables',
subtext: 'Circular layout',
top: 'bottom',
left: 'right'
},
tooltip: {},
legend: [{
data: categories.map(function (a) {
return a.name;
})
}],
animationDurationUpdate: 1500,
animationEasingUpdate: 'quinticInOut',
series: [
{
name: 'Les Miserables',
type: 'graph',
layout: 'circular',
circular: {
rotateLabel: true
},
data: graph.nodes,
links: graph.links,
categories: categories,
roam: true,
label: {
position: 'right',
formatter: '{b}'
},
lineStyle: {
color: 'source',
curveness: 0.3
}
}
]
};
myChart.setOption(option);
}, 'xml');
Github Sample Codes
The github of this graph has the source code for the JSON file (codes) that it uses to populate the graph -> https://github.com/hecore/echart_demo/blob/master/data/hecore.json
I'm not sure how did the codes transform to this -> https://github.com/hecore/echart_demo/blob/master/data/les-miserables.json
Lastly, this is the file that they used to populate in the echarts circular layout graph in .gexf format -> https://github.com/hecore/echart_demo/blob/master/data/les-miserables.gexf

You could install Gephi (https://gephi.org/users/install/), then the JSON Exporter plugin for Gephi (https://gephi.org/plugins/#/plugin/jsonexporter-plugin). Then open the gexf file in Gephi and go to file>export>graph file>json graph. I'm not sure if it's exactly the format you need, but could be a starting point.

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()

Highcharts downsampling - CSV

I'm developping a web-app and I use the JS Highcharts plugin to help me to draw some charts. Sometimes I load a CSV file with more than 100 000 lines with 4 columns.
Obviously, the chart plugin meet some problems. So, I can't downsample my CSV file directly but, I found a Downsampling Highcharts plugin (http://www.highcharts.com/plugin-registry/single/13/Highcharts-Downsample) that do the job !
But in fact, this plugin may only initialize a serie with a threshold value .. And I don't know how to apply this method on my series loaded by CSV ..
I load my CSV like that instead of "series" attribute specified by the plugin Usage :
data: {csv: csv},
The plugin doc tells us to use it like that :
series: [{
downsample: {
threshold: 1000 // 0 disables downsampling for this series.
},
data: // Your data (array of arrays with two values or array of numerical values)
}]
But I don't use "series" attribute because I load my series directly from a CSV file ..
So, I want to find a solution to downsample my CSV file using this Downsampling Hicharts plugin ..
Thank you so much !
So, finally, i found a solution !
I parse my CSV file myself and I can specify the downsample attribute :
var options = { //Initialize my chart's option
chart: {
zoomType: 'x',
renderTo: $('#chart-'+unused)[0]
},
title: {
text: elem.title
},
credits: {
enabled: false
},
xAxis: {
categories: [], //initialize empty category array
type: "line"
},
yAxis: {
title: {
text: "milli-SI"
}
},
series: [] //initialize empty serie array
};
var lines = csv.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if (lineNo == 0) {
$.each(items, function(itemNo, item) {
if (itemNo > 0) {
var series = {
data: [],
name: item,
downsample : {threshold: 2000} //initialize downsample for a specific serie
};
options.series.push(series);
}
});
}
else {
$.each(items, function(itemNo, item) {
if (item.length == 0)
return;
if (itemNo == 0) {
options.xAxis.categories.push(item);
} else {
options.series[itemNo -1].data.push(parseFloat(item));
}
});
}
});
var chart = new Highcharts.Chart(options);

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>

Displaying a json file with highstock

I have some difficulties displaying a graph with Highstock. It seems like I can't have access to the x-axis part where the graph should be displayed. I am new with Highstocks so my code could seem like a mess but my idea was the following:
First access the json file from the server. Convert it in the right format [[datestamp, value], ....]. Then display the graph.
Here is my Json file (file.json):
[{"date":"2013-10-04T22:31:12.000Z","value":30000},{"date":"2013-10-04T22:31:58.000Z","value":35000},{"date":"2013-10-04T22:32:05.000Z","value":60000},{"date":"2013-10-04T22:32:12.000Z","value":45000}]
My code is the following:
$(function() {
chartOjb = new Object();
var mydata = [];
$.getJSON('file.json', function(data) {
$.each(data, function (index, item) {
chartOjb.name = getTimestamp(item.date);
chartOjb.data = item.value;
mydata.push({ x: chartOjb.name, y: parseFloat(chartOjb.data) });
});
$('#container').highcharts('StockChart', {
chart: {
type: 'candlestick',
zoomType: 'x'
},
navigator: {
adaptToUpdatedData: false,
series: {
data: mydata
}
},
scrollbar: {
liveRedraw: false
},
xAxis: {
type: 'datetime',
title: 'Time',
//minRange: 3600 * 1000/15 // one hour
},
rangeSelector : {
selected : 1
},
title : {
text : value
},
series : [{
name : 'Capacité',
data : data,
tooltip: {
valueDecimals: 2
}
}] }); });
});
Thank you very much for your help
Could you add your function getTimestamp()? Maybe there is something wrong.
Keep in mind that:
x-value should be timestamp,
when using a lot of objects { x: x, y: y }, set turboThreshold

How to save an image of the chart on the server with highcharts?

With highcharts, you have a built-in button to download the current chart (example: http://www.highcharts.com/demo/, this button: ). You can save it as PNG, JPEG, PDF or SVG.
What I'd like to do is to create a link that saves the image on the server, instead of downloading it. How could I do that ?
I suppose that I have to modify the exportChart function in the exporting.src.js file. It looks like this (but I don't know javascript enough to do that) :
exportChart: function (options, chartOptions) {
var form,
chart = this,
svg = chart.getSVG(chartOptions);
// merge the options
options = merge(chart.options.exporting, options);
// create the form
form = createElement('form', {
method: 'post',
action: options.url
}, {
display: NONE
}, doc.body);
// add the values
each(['filename', 'type', 'width', 'svg'], function (name) {
createElement('input', {
type: HIDDEN,
name: name,
value: {
filename: options.filename || 'chart',
type: options.type,
width: options.width,
svg: svg
}[name]
}, null, form);
});
// submit
form.submit();
// clean up
discardElement(form);
},
It could be done really easy with PhantomJS. You can render Highchart chart and save it to SVG, PNG, JPEG or PDF. The example below renders a demo Highcharts diagram to SVG and PDF at the same time:
var system = require('system');
var page = require('webpage').create();
var fs = require('fs');
// load JS libraries
page.injectJs("js/jquery.min.js");
page.injectJs("js/highcharts/highcharts.js");
page.injectJs("js/highcharts/exporting.js");
// chart demo
var args = {
width: 600,
height: 500
};
var svg = page.evaluate(function(opt){
$('body').prepend('<div id="container"></div>');
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
width: opt.width,
height: opt.height
},
exporting: {
enabled: false
},
title: {
text: 'Combination chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Bananas', 'Plums']
},
yAxis: {
title: {
text: 'Y-values'
}
},
labels: {
items: [{
html: 'Total fruit consumption',
style: {
left: '40px',
top: '8px',
color: 'black'
}
}]
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
},
series: {
enableMouseTracking: false,
shadow: false,
animation: false
}
},
series: [{
type: 'column',
name: 'Andrii',
data: [3, 2, 1, 3, 4]
}, {
type: 'column',
name: 'Fabian',
data: [2, 3, 5, 7, 6]
}, {
type: 'column',
name: 'Joan',
data: [4, 3, 3, 9, 0]
}, {
type: 'spline',
name: 'Average',
data: [3, 2.67, 3, 6.33, 3.33],
marker: {
lineWidth: 2,
lineColor: 'white'
}
}, {
type: 'pie',
name: 'Total consumption',
data: [{
name: 'Andrii',
y: 13,
color: '#4572A7'
}, {
name: 'Fabian',
y: 23,
color: '#AA4643'
}, {
name: 'Joan',
y: 19,
color: '#89A54E'
}],
center: [100, 80],
size: 100,
showInLegend: false,
dataLabels: {
enabled: false
}
}]
});
return chart.getSVG();
}, args);
// Saving SVG to a file
fs.write("demo.svg", svg);
// Saving diagram as PDF
page.render('demo.pdf');
phantom.exit();
If you save the code as demo.js, then just run bin/phantomjs demo.js to generate demo.svg and demo.pdf
I just implement this using Nobita's method. I was creating a survey that showed the user's results in a chart, uploaded the image to my server and then sent out an email with the image in it. Here's a few things to note.
I had to make a few updates to the highcharts/exporting-server/index.php file which are the following:
I changed the directory from "temp" to something else and just note that it is in 4 different locations.
I had to change shell_exec() adding "-XX:MaxHeapSize=256m" because it was giving me an error:
$output = shell_exec("java -XX:MaxHeapSize=256m -jar ". BATIK_PATH ." $typeString -d $outfile $width /mypathhere/results/$tempName.svg");
If you want it to download that image you can leave the following alone:
header("Content-Disposition: attachment; filename=$filename.$ext");
header("Content-Type: $type");
echo file_get_contents($outfile);
But, I changed this because I wanted to send back the path to the image, so I deleted the above and replace this with the image path (Note that I'm just using the temporary name.):
echo "/mypathhere/results/$tempName.$ext";
Also, this file is deleting the svg file and also the new file you made. You need to remove the code that deletes the file:
unlink($outfile);
And you can also delete the line before it if you want to keep the svg file.
Make sure to include highcharts/js/modules/exporting.js
Then, in your JS you can do something like the following:
var chart = new Highcharts.Chart();
var imageURL = '';
var svg = chart.getSVG();
var dataString = 'type=image/jpeg&filename=results&width=500&svg='+svg;
$.ajax({
type: 'POST',
data: dataString,
url: '/src/js/highcharts/exporting-server/',
async: false,
success: function(data){
imageURL = data;
}
});
The URL you are posting to is the new version of the /exporting-server/index.php. Then, you can use the imageURL however you like.
I haven't done that before, but I believe you want to play with the index.php file located in the exporting-server folder.
By default Highcharts provides (for free) a web service but you can modify that and create your own web service for exporting, or do whatever you want with the chart. Look at these instructions which can be found here Export module:
"If you want to set up this web service on your own server, the index.php file that handles the POST is supplied in the download package inside the /exporting-server directory.
Make sure that PHP and Java is installed on your server.
Upload the index.php file from the /exporting-server directory in
the download package to your server.
In your FTP program, create directory called temp in the same
directory as index.php and chmod this new directory to 777
(Linux/Unix servers only).
Download Batik from http://xmlgraphics.apache.org/batik/#download.
Find the binary distribution for your version of jre
Upload batik-rasterizer.jar and the entire lib directory to a
location on your web server. In the options in the top of the
index.php file, set the path to batik-rasterier.jar.
In your chart options, set the exporting.url option to match your
PHP file location. "
You can try this
var chart = $('#yourchart').highcharts();
svg = chart.getSVG();
var base_image = new Image();
svg = "data:image/svg+xml,"+svg;
base_image.src = svg;
$('#mock').attr('src', svg);
Take html of Mock and send to DB or save only the binary code .
Save highchart as binary image

Categories

Resources