I'm using my Ubuntu server to run automated speed tests and am recording the data in a csv file. I'd like to now plot all this data in a graph. The csv file is called data.csv in the same directory as index.html and it contains the following:
time,ping,down,up
1454190169992.8655,25.40,61.1,18.2
1454196940589.804,24.57,65.8,18.2
1454200093536.6118,26.39,66.8,18.2
1454235805528.2244,25.21,59.3,18.1
1454235966417.7297,25.01,59.4,18.2
1454236051628.0317,24.68,59.8,18.2
1454239827546.229,26.63,64.6,18.2
index.html currently looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="nv.d3.css" />
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="nv.d3.min.js"></script>
</head>
<body>
<svg id="chart" style="width:500; height:500;"></svg>
</body>
<script type="text/javascript">
d3.csv("data.csv", function(error, data){
console.log(data)
// create an empty object that nv is expecting
var exampleData = [
{
key: "totals",
values: []
}
];
// populate the empty object with your data
data.forEach(function (d){
d.value = +d.value
exampleData[0].values.push(d)
})
nv.addGraph(function() {
var chart = nv.models.lineChart()
.margin({left: 100}) //Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
.x(function (d) { console.log(d); return d.time })
.y(function (d) { return d.ping })
d3.select('#chart')
.datum(exampleData)
.attr("id", function (d) { console.log(d); })
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
});
</script>
</html>
Related
I'm trying to convert a wordtree Google visualization to an image. The current code below runs the wordtree so I can see the visual, but I can't figure out the last section to convert to an image or export as an image. (var my_div = section to end)
I have tried changing code from link below, but can't get it to save as an image.
https://developers.google.com/chart/interactive/docs/printing
I'm also doing this inside of jsfiddle.net to try and make this work.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current'); // Don't need to specify chart libraries!
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
google.visualization.drawChart({
"containerId": "mywordtree",
"dataSourceUrl": "https://docs.google.com/spreadsheets/d/1vi-YzV7s7eZ25938Q57DbZvT0iqggiCqRvDgxeZtP6c/edit?usp=sharing",
"query":"SELECT A",
"chartType": "WordTree",
"options": {
wordtree: {
format: 'implicit',
//alt type is 'suffix', 'prefix'
type: 'suffix',
word: 'prescription'
}
}
});
}
var my_div = document.getElementById('chart_div');
var my_chart = new google.visualization.ChartType(mywordtree);
google.visualization.events.addListener(my_chart, 'ready', function () {
mywordtree.innerHTML = '<img src="' + my_chart.getImageURI() + '">';
});
my_chart.draw(data);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="mywordtree" style="width: 1000px; height: 1000px;"></div>
</body>
</html>
first, in order to generate an image of the chart,
you need to wait for the chart's 'ready' event.
in order to wait for the 'ready' event,
you need access to the chart object.
you will not be able to use the google.visualization.drawChart method,
because it does not return a handle to the chart.
next, the WordTree chart, does not have a method for getImageURI,
so you will need to create the image manually, from a blob.
see following working snippet...
google.charts.load('current').then(function () {
// get chart container
var container = document.getElementById('mywordtree');
// create chart
var chart = new google.visualization.ChartWrapper({
chartType: 'WordTree',
containerId: container.id,
dataSourceUrl: 'https://docs.google.com/spreadsheets/d/1vi-YzV7s7eZ25938Q57DbZvT0iqggiCqRvDgxeZtP6c/edit?usp=sharing',
options: {
wordtree: {
format: 'implicit',
//alt type is 'suffix', 'prefix'
type: 'suffix',
word: 'prescription'
}
}
});
// listen for ready event
google.visualization.events.addListener(chart, 'ready', function () {
var domUrl; // object url
var image; // chart image
var imageUrl; // chart image url
var svg; // svg element
// add svg namespace to chart
svg = container.getElementsByTagName('svg')[0];
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
// create image url from svg
domUrl = window.URL || window.webkitURL || window;
imageUrl = domUrl.createObjectURL(new Blob([svg.outerHTML], {type: 'image/svg+xml'}));
// create chart image
image = new Image();
image.onload = function() {
// replace chart with image
container.innerHTML = image.outerHTML;
}
image.src = imageUrl;
});
// draw chart
chart.draw();
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="mywordtree"></div>
I am trying to build tables based on JSON data using D3.js.
My example HTML file is:
<!DOCTYPE html>
<meta charset='utf-8'>
<html>
<head>
<script src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script>
</head>
<body>
<table id="muell"></table>
<script type='text/javascript' src='script.js'></script>
<script>
var intern_data = [{
Proton: "A",
Multiplett: "dd",
Formel: "\<sup\>1\</sup\>H\<sub\>3\</sub\>"
},
{
Proton: "B",
Multiplett: "dq",
Formel: "<sup>1</sup>C<sub>3</sub>"
}
];
var spalten = ['Proton', 'Multiplett', 'Formel'];
tabulate("#muell", intern_data, spalten);
</script>
</body>
</html>
The Javascript is stolen from from bl.ocks.org and became a little bit modified to add the new table content into a preformatted region.
var tabulate = function (table_id,data, columns) {
var table = d3.select(table_id)
var thead = table.append('thead')
var tbody = table.append('tbody')
thead.append('tr')
.selectAll('th')
.data(columns)
.enter()
.append('th')
.text(function (d) {
return d
})
var rows = tbody.selectAll('tr')
.data(data)
.enter()
.append('tr')
var cells = rows.selectAll('td')
.data(function (row) {
return columns.map(function (column) {
return {
column: column,
value: row[column]
}
})
})
.enter()
.append('td')
.text(function (d) {
return d.value
})
return table;
}
In principle everything works fine as long as I use plain text. Unfortunately
HTML tags become modified. For instance ">" becomes "_gt;" (& instead of _, cannot use it here, otherwise the expression becomes ">" :-) ).
I tried to use \ to keep pure HTML, but this doesn't seem to work.
d3 has two functions, text and html. If you want to output html you can use the html function instead:
var cells = rows.selectAll('td')
.data(function (row) {
return columns.map(function (column) {
return {
column: column,
value: row[column]
}
})
})
.enter()
.append('td')
.html(function (d) {
return d.value
})
But be careful, this is dangerous if the value doesn't come from a trusted source - since a user might be able to inject malicious HTML.
being new to plotting chart with the external api data and lack of knowldge leads me to ask
HOw to plot a chart with coingeko charts api data? link to get json formated api data is:
https://api.coingecko.com/api/v3/coins/ethereum/market_chart?vs_currency=btc&days=30
i had used this sample code and replace the link however only empty chart gets populated without plotting any data points
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text:"Rendering Chart with dataPoints from External JSON"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
$.getJSON("https://api.coingecko.com/api/v3/coins/mustangcoin/market_chart?vs_currency=btc&days=max&type=json", function(data) {
$.each(data, function(key, value){
dataPoints.push({x: value[0], y: parseInt(value[1])});
});
chart.render();
});
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
The API returns:
{
prices: Array,
market_caps: Array,
total_volumes: Array,
}
First you need to select which data you want, you cannot mix them up together.
Secondly, you should create chart new CanvasJS.Chart after you have received the JSON result (in the function() {} body, not before that. Right now, it is uncertain whether the chart is actually getting the updated dataPoints, or is aware about it being updated after you have created the chart.
If you want to update the chart after creation you need to do what their docs says: https://canvasjs.com/docs/charts/basics-of-creating-html5-chart/updating-chart-options/
Murray (2017) suggests the following code for loading a csv file and parsing columns usign D3.js V4. This code no longer works in V5. How can it be restructured in order to work? Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Line chart</title>
<script type="text/javascript" src="/../../d3.js"></script>
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript">
var dataset;
//Function for converting CSV values from strings to Dates and numbers
var rowConverter = function(d) {
return {
date: new Date(+d.year, (+d.month - 1)), //Make a new Date object for each year + month
average: parseFloat(d.average) //Convert from string to float
};
}
//Load in data
d3.csv("mauna_loa_co2_monthly_averages.csv", rowConverter, function(data) {
var dataset = data;
//Print data to console as table, for verification
console.table(dataset, ["date", "average"]);
}
For v5, d3-fetch is your friend as d3-request has been deprecated.
For instance:
d3.csv("/path/to/file.csv", rowConverter).then(function(data){ do whatever })
I am trying to plot circles on a map based on data from csv files. I want the latitude and longitude from the csv file and plot a circle.
I am unable to long the two fields. I get an object undefined error. Here's my code so far:
Here's the link for the CSV file -
http://slate-interactives-prod.elasticbeanstalk.com/gun-deaths/getCSV.php
<html>
<head>
<meta charset="utf-8">
<link href="d3-geomap/css/d3.geomap.css" rel="stylesheet">
<script src="d3-geomap/vendor/d3.geomap.dependencies.min.js"></script>
<script src="d3-geomap/js/d3.geomap.min.js"></script>
</head>
<style>
path.unit:hover{
fill:#99d8c9;
}
</style>
<body>
<div id="map"></div>
</body>
</html>
<script>
var map = d3.geomap.choropleth()
.geofile('d3-geomap/topojson/countries/USA.json')
.projection(d3.geo.albersUsa)
.column('2012')
.unitId('fips')
.scale(1000)
.legend(true);
var width = 950,
height = 550;
// set projection
var projection = d3.geo.albersUsa();
// create path variable
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.csv("data.csv", function(data) {
var coordinates = projection([data.lat,data.lng]);
svg.append("circle")
.attr("cx", coordinates[0])
.attr("cy", coordinates[1])
.attr("r", 5)
.style("fill", "red");
});
d3.select('#map')
.call(map.draw, map);
</script>
There are at least a couple of problems in your code. First the data object that d3.csv retrieves is an array. It's the elements of that array that will have properties such as .lat and .lng. So data.lat and data.lng are not defined.
I'm guessing that you want to create circles for each element in the array. You could do that by iterating through the array, e.g.
data.forEach(function(d) {
var coordinates = projection([d.lat, d.lng]);
// ...
});
That's not the normal D3 idiom (it's not using selections and .enter()) but it would work.
Secondly, CSV files are always read as text strings, even when the values are actually numbers. You'll want to convert from strings to numbers, so the code above really should be
var coordinates = projection([parseFloat(d.lat), parseFloat(d.lng)]);
As I said, there may be other problems with your code, but fixing those two should at least get you further along.