How can I parse column of .csv file instead of writing the values manually - html

I want to be able to represent a bar chart by using only two columns in my .csv file, I have written a temporary solution by writing manually the values of the columns.. But if I have more columns, or more values in every column it may become impossible to write it manually. I'd love to get some help on how to transform my code to read the columns from the .csv file, so far I've been able to get a single bar chart and wasn't able to further edit the code for using more columns to get a multiple bar chart. Also, after finding the code for multiple bar charts - it traversed on all the columns on the .csv file and it showed all the columns in the chart, then when I tried editing the for loop for just the first two columns, and it didn't work, so I decided to write it manually for now.
Question: How to read .csv columns for bar chart representation (just two columns) instead of writing the column's values manually as I did.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: ""
},
axisX:{
title: "car type"},
axisY:{
title:"$",
interval: 5000,
},
data: [
{
type: "column",
yValueFormatString: "#.####",
showInLegend: true,
name: "DealerCost",
dataPoints: [
{ "label": "Regular", y: 27446.14286 },
{ "label": "Sports.car", y: 48473.16327 },
{ "label": "SUV", y: 31625.35},
{ "label": "Wagon", y: 26645.63333 },
{ "label": "Minivan", y: 25355.5 },
{ "label": "Pickup", y: 22616.75},
]
},
{
type: "column",
showInLegend: true,
name: "RetailPrice",
yValueFormatString: "#.####",
dataPoints: [
{ "label": "Regular", y: 29814.3591836735 },
{ "label": "Sports.car", y: 53387.06122 },
{ "label": "SUV", y: 34790.25},
{ "label": "Wagon", y: 28840.53333 },
{ "label": "Minivan", y: 27796.5 },
{ "label": "Pickup", y: 24941.375},
]
},
]
});
chart.render();
}
</script>
<div id="chartContainer" style="height: 100%; width: 50%;">
</body>
</html>

Related

Not sure how to use Vega-Lite chart examples - seem to be partial code

I got the following Vega-Lite code example from Observable and it works great:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="https://cdn.jsdelivr.net/npm/vega#5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite#4"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite-api#4"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-tooltip"></script>
</head>
<body>
<div id="view"></div>
<script>
// Setup API options.
const options = {
config: {
// Vega-Lite default configuration.
},
init: (view) => {
// Initialize tooltip handler.
view.tooltip(new vegaTooltip.Handler().call);
},
view: {
// View constructor options.
// Remove the loader if you don't want to default to vega-datasets!
//loader: vega.loader({
// baseURL: "https://cdn.jsdelivr.net/npm/vega-datasets#2/",
//}),
renderer: "canvas",
},
};
// Register vega and vega-lite with the API.
vl.register(vega, vegaLite, options);
// Now you can use the API!
vl.markBar({ tooltip: true })
.data([
{ a: "A", b: 28 }, { a: "B", b: 55 }, { a: "C", b: 43 },
{ a: "D", b: 91 }, { a: "E", b: 81 }, { a: "F", b: 53 },
{ a: "G", b: 19 }, { a: "H", b: 87 }, { a: "I", b: 52 },
])
.encode(
vl.x().fieldQ("b"),
vl.y().fieldN("a"),
vl.tooltip([vl.fieldN("a"), vl.fieldQ("b")])
)
.render()
.then(viewElement => {
// Render returns a promise to a DOM element containing the chart.
// viewElement.value contains the Vega View object instance.
document.getElementById('view').appendChild(viewElement);
});
</script>
</body>
</html>
However when I look at the Vega-Lite examples (for example this) they only have a block of code between {}. How can I use that block of code between the {} in html to replicate their example? I have tried various ways but I just keep on getting blank pages. Not sure where to find the documentation relating to this. Also the example code sometimes refers to vega-lite#5, should I change my references to vega-lite#4 accordingly?
You will need vega-lite, vega-cli and vega-embed to create a vega-lite chart. You can check the devDependencies for the selected version of vega-lite. For example, in package.json of vega-lite v5.1.0, these are the required dependencies:
"vega-cli": "^5.20.2",
"vega-embed": "^6.18.2",
For more details on installation refer this.
After adding these dependencies, you can just create a div with id and in that div you can embed your vega-lite configuration as provided in its vega-editor and embedded in jsfiddle. Below is the snippet and documentation for latest configurations.
var yourVlSpec = {
"$schema": "https://vega.github.io/schema/vega-lite/v5.0.json",
"description": "A simple bar chart with embedded data.",
"data": {
"values": [{
"a": "A",
"b": 28
}, {
"a": "B",
"b": 55
}, {
"a": "C",
"b": 43
},
{
"a": "D",
"b": 91
}, {
"a": "E",
"b": 81
}, {
"a": "F",
"b": 53
},
{
"a": "G",
"b": 19
}, {
"a": "H",
"b": 87
}, {
"a": "I",
"b": 52
}
]
},
"mark": "bar",
"encoding": {
"x": {
"field": "a",
"type": "ordinal"
},
"y": {
"field": "b",
"type": "quantitative"
}
}
}
vegaEmbed("#vis", yourVlSpec);
<script src="https://cdn.jsdelivr.net/combine/npm/vega#5.20.2,npm/vega-lite#5.0.0,npm/vega-embed#6.17.0"></script>
<body>
<div id="vis"></div>
</body>

Why is Leaflet Ajax not processing and displaying GeoJSON data?

I have been trying for weeks to get Leaflet Ajax to accept data requests from the Land Information New Zealand (LINZ) API without success.
I have a valid key (not included in the snippet) and have tried several tests to load this data in. Other datasets from the LINZ API do not worth either.
What am I doing wrong here?
<html>
<head>
<!-- Style -->
<link rel="stylesheet" href="css/style.css">
<!-- Leaflet -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<!-- Leaflet Ajax -->
<script type='text/javascript' src="./js/leaflet.ajax.js"></script>
<div id="map"></div>
</head>
<body>
<script>
map = L.map('map').setView([-41.29132, 174.77931],16)
var OpenTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
maxZoom: 17,
attribution: 'Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)'
});
OpenTopoMap.addTo(map)
property_tiles_link = "https://data.linz.govt.nz/services/query/v1/vector.json?key=KEY_GOES_HERE&layer=50804&x=172.61706383056807&y=-43.57379489129212&max_results=3&radius=10000&geometry=true&with_field_names=true"
geojson = new L.GeoJSON.AJAX(property_tiles_link).addTo(map)
console.log(geojson)
overlays = {
"geojson": geojson
}
basemaps = {
"OpenTopoMap": OpenTopoMap
}
L.control.layers(basemaps, overlays).addTo(map)
</script>
</body>
The code snippet results in this output:
Looking through the logged GeoJSON object does not seem to show any successfully parsed data. The error message in Firefox translates roughly to "The configuration of HTML characters hasn't been declared. The document will show 'rubbish' text in some configurations of the browser."
Any ideas would be super helpful!
An example of the response:
{
"vectorQuery": {
"layers": {
"50804": {
"crs": {
"type": "name",
"properties": {
"name": "EPSG:4326"
}
},
"field_names": ["id", "title_no", "status", "type", "land_district", "issue_date", "guarantee_status", "estate_description", "number_owners", "spatial_extents_shared"],
"type": "FeatureCollection",
"features": [{
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[175.4776337167, -41.2221699],
[175.4782420833, -41.2225527833],
[175.4801549333, -41.2237566167],
[175.476269, -41.2259343],
[175.47357595, -41.22444375],
[175.4776337167, -41.2221699]
]
]
]
},
"distance": 0,
"type": "Feature",
"properties": {
"id": 1468560,
"title_no": "WN53B/277",
"status": "LIVE",
"type": "Freehold",
"land_district": "Wellington",
"issue_date": "1998-04-16 00:00:00",
"guarantee_status": "Guarantee",
"estate_description": "Fee Simple, 1/1, Lot 1 Deposited Plan 85426, 110,945 m2",
"number_owners": 1,
"spatial_extents_shared": false
},
"id": 1191838
}, {
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[175.48005638330002, -41.2282570333],
[175.48105425000003, -41.2286012667],
[175.4789359, -41.2297867333],
[175.47874645, -41.2298923],
[175.4767530167, -41.2310074667],
[175.47604405, -41.2314040667],
[175.47550265, -41.23170695000001],
[175.4749415833, -41.2320208833],
[175.4745023167, -41.2322666333],
[175.474015, -41.2317699833],
[175.4735909, -41.23133785000001],
[175.4735833, -41.2313303667],
[175.4732046667, -41.23094425],
[175.4728425667, -41.2305752833],
[175.4725057833, -41.2302328833],
[175.4722412333, -41.2299625],
[175.4719444667, -41.2296600833],
[175.4715930333, -41.22930195],
[175.47127355, -41.2289763667],
[175.4712437333, -41.2289459833],
[175.4708617, -41.22855675],
[175.4704157833, -41.2281024167],
[175.4699766167, -41.227654983300006],
[175.4692410167, -41.2269055],
[175.4692395833, -41.2269040667],
[175.46921793330003, -41.2268834667],
[175.4718439333, -41.2254143333],
[175.4733724167, -41.2245578167],
[175.48005638330002, -41.2282570333]
]
]
]
},
"distance": 134,
"type": "Feature",
"properties": {
"id": 2348803,
"title_no": "WN103/58",
"status": "LIVE",
"type": "Freehold",
"land_district": "Wellington",
"issue_date": "1899-10-23 00:00:00",
"guarantee_status": "Guarantee",
"estate_description": "Fee Simple, 1/1, Lot 75 Deposited Plan 579, 409,390 m2",
"number_owners": 1,
"spatial_extents_shared": true
},
"id": 5113879
}, {
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[175.48005638330002, -41.2282570333],
[175.48105425000003, -41.2286012667],
[175.4789359, -41.2297867333],
[175.47874645, -41.2298923],
[175.4767530167, -41.2310074667],
[175.47604405, -41.2314040667],
[175.47550265, -41.23170695000001],
[175.4749415833, -41.2320208833],
[175.4745023167, -41.2322666333],
[175.474015, -41.2317699833],
[175.4735909, -41.23133785000001],
[175.4735833, -41.2313303667],
[175.4732046667, -41.23094425],
[175.4728425667, -41.2305752833],
[175.4725057833, -41.2302328833],
[175.4722412333, -41.2299625],
[175.4719444667, -41.2296600833],
[175.4715930333, -41.22930195],
[175.47127355, -41.2289763667],
[175.4712437333, -41.2289459833],
[175.4708617, -41.22855675],
[175.4704157833, -41.2281024167],
[175.4699766167, -41.227654983300006],
[175.4692410167, -41.2269055],
[175.4692395833, -41.2269040667],
[175.46921793330003, -41.2268834667],
[175.4718439333, -41.2254143333],
[175.4733724167, -41.2245578167],
[175.48005638330002, -41.2282570333]
]
]
]
},
"distance": 134,
"type": "Feature",
"properties": {
"id": 4177014,
"title_no": "94991",
"status": "LIVE",
"type": "Leasehold",
"land_district": "Wellington",
"issue_date": "2003-06-10 09:00:00",
"guarantee_status": "Guarantee",
"estate_description": "Leasehold, 1/1, Lot 75 Deposited Plan 579, 409,390 m2",
"number_owners": 1,
"spatial_extents_shared": true
},
"id": 5116291
}]
}
}
}
}
The Leaflet-ajax plugin expects directly a GeoJSON compliant object in the loaded data, whereas in the sample response you show, the structure of the response is:
{
"vectorQuery": {
"layers": {
[layerId]: {
// GeoJSON FeatureCollection
}
}
}
}
Therefore you have to convert this data into a GeoJSON object first. Here in this case it looks quite simple, as you just have to extract the FeatureCollection. You can use leaflet-ajax middleware option to perform this conversion between the reception of the data and before it is processed to be transformed into Leaflet layers:
new L.GeoJSON.AJAX("url", {
middleware(rawData) {
// Extract the GeoJSON FeatureCollection
const layerId = 50804;
return rawData.vectorQuery.layers[layerId];
}
});

Google Embed API: GEO chart - show specific country

I'm using Google Embed API to show data from google analytics visually.
I was trying to display only a specific country to show users from each of its regions.
I create a "DataChart" which has a "query" and "chart" object. In the chart object, you specify a type of chart, and some extra options.
If I choose "GEO", then it will use the "Geocoding" api, as I've understood it.
I am not able to show the country (Sweden) with its regions however, I don't know what to specify in the chart "options" object.
var location = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': viewId,
'start-date': '90daysAgo',
'end-date': 'today',
'metrics': 'ga:users',
'sort': '-ga:users',
'dimensions': 'ga:region',
'max-results': 10
},
chart: {
'container': 'location',
'type': 'GEO',
'options': {
region: 150, // <-- Europe
country: 'SE', // <-- just guessing
}
}
});
This shows the whole world. If I remove "country", it shows Europe, with the top part cropped away. So I haven't specified "country" in the correct way (I am only guessing since there is no info).
The only info I can find on the GEO chart is here Visualization: GeoChart, but it's not specific for the Embed API.
So does anyone have a solution for this case, and is there info on different properties for the chart object? ( For the query object, there is Dimensions & Metrics Explorer )
Update:
The main question was solved with a below answer:
'options': {
region: 'SE',
resolution: 'provinces'
}
, but the data is not displayed in the regions, so if you have any clues around that, you could perhaps mention it as a comment.
Here is part of the data response from the query (with regions):
"dataTable": {
"cols": [
{
"id": "ga:region",
"label": "ga:region",
"type": "string"
},
{
"id": "ga:users",
"label": "ga:users",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "Stockholm County"
},
{
"v": "15"
}
]
},
{
"c": [
{
"v": "Vastra Gotaland County"
},
{
"v": "6"
}
]
},
here are the only configuration options for the GeoChart that I'm aware of...
to display only sweden...
var options = {
region: 'SE'
};
(remove the country option)
see following working snippet...
google.charts.load('current', {
'packages':['geochart'],
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
]);
var options = {
region: 'SE',
resolution: 'provinces'
};
var chart = new google.visualization.GeoChart(document.getElementById('chart'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

c3.js generate a stacked bar from JSON payload

I am attempting to generate a stacked bar chart with c3 when using a JSON payload (code below). However, when I group the data, instead of having a stacking behavior, they overlay instead. If I use the column structure, I get the intended behavior, but this means that I'd have different code generate for a stacked bar chart versus my other visuals (ie timeseries chart).
var chart = c3.generate({
data: {
x: "x-axis",
json:[
{ "x-axis": "0",
"data1": 30
},
{ "x-axis": "0",
"data2": 40
}],
keys: {
x: "x-axis",
value: ["data1", "data2"]
},
groups: [
['data1', 'data2']
],
type: 'bar'
}
});
Here is a fiddle: http://jsfiddle.net/cjrobinson/ozf4fzcb/
It's weird they overplot each other in your example, I'd report that as a bug to c3
If you don't want to use the columns[] format, you could do it like below, would still need some data wrangling though:
var chart = c3.generate({
data: {
x: "x-axis",
json:[
{ "x-axis": "0",
"data1": 30,
"data2": 40
},
{ "x-axis": "1",
"data1" :20,
"data2": 60
}],
// etc etc
keys: {
x: "x-axis",
value: ["data1", "data2"]
},
groups: [
['data1', 'data2']
],
type: 'bar'
}
});
http://jsfiddle.net/dhgujwy7/1/

Highcharts - Passing in Color with JSON

Currently, I'm using a back end process to create a JSON file for a 3d bar chart with HighCharts.
[{
"name": "Town",
"data": ["NorthCentral","NorthEast","SouthCentral","SouthEast","West"]
}, {
"name": "Population",
"data": [99.47,82,89,82,82]
}]
What I would like know is - can you pass in colors with each data point? for example:
[{
"name": "Town",
"data": ["NorthCentral","NorthEast","SouthCentral","SouthEast","West"]
}, {
"name": "Population",
"data": [{color: 'red',99.47},82,89,82,82]
}]
I have tried already with no luck. This might not be supported but I thought I would ask.
Try something like
data: [{
name: 'Point 1',
color: '#00FF00',
y: 0
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
A sample with line chart