-
Notifications
You must be signed in to change notification settings - Fork 6
/
iNatAPIv1_observation_histogram.html
255 lines (242 loc) · 10.3 KB
/
iNatAPIv1_observation_histogram.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, minimum-scale=0.6">
<meta name="description" content="iNaturalist API Observation Histogram" />
<title>iNaturalist API Observation Histogram</title>
<style>
html,body { font:14px Sans-Serif; }
#main { width:100%; }
table, thead, tbody, tr, td, th { margin:0; padding:4px; border-width:1px 0px;border-style:solid; border-color:lightgray; border-spacing:0; border-collapse:collapse; }
th { position:-webkit-sticky /*Safari*/; position:sticky; top:0; font-weight:600; background:forestgreen; color:white; text-align:left; vertical-align:bottom; }
tr { background:whitesmoke; }
tr:nth-child(even) { background-color:white; }
.tar { text-align:right; }
a { text-decoration:none; color:royalblue; }
a:hover { background:lightgray; }
tfoot tr { font-weight:600; background:black; color:white; }
</style>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
let winurlstr = window.location.href;
let winurlsearchstr = window.location.search;
let winurlexsearchstr = winurlstr.replace(winurlsearchstr,'');
let winurlparams = new URLSearchParams(winurlsearchstr.substring(1));
let p_date_field = winurlparams.get('date_field');
let l_date_field = ( p_date_field==='created' ) ? 'Created' : 'Observed'; // default is observed
let p_interval = winurlparams.get('interval');
let l_interval = ( p_interval==='year' ) ? 'Year'
: ( p_interval==='month' ) ? 'Month'
: ( p_interval==='week' ) ? 'Week'
: ( p_interval==='day' ) ? 'Day'
: ( p_interval==='hour' ) ? 'Hour'
: ( p_interval==='week_of_year' ) ? 'Week of Year'
: 'Month of Year'; // default is month_of_year
function furl(url,txt=url) { return '<a href="'+url+'">'+txt+'</a>'; };
function famp(str) { return str.replace(/&/g,'&'); };
function fcomnum(n) { return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,',') };
function fpct(d,p=1) {
x = d*100;
return x.toFixed(p);
};
function faddelem(etype,eparent=null,eattributes={}) {
let eobj = document.createElement(etype);
for (let [key,value] of Object.entries(eattributes)) {
if ( typeof value === 'object' && value !== null ) {
for (let [subkey,subvalue] of Object.entries(value)) { eobj[key][subkey] = subvalue; };
}
else { eobj[key] = value; };
};
if (eparent) { eparent.appendChild(eobj); };
return eobj;
};
function faddelems(etype,eparent=null,eattributes=[]) { for (let e of eattributes) { faddelem(etype,eparent,e); }; };
function fresults(xobj) {
let results = xobj.results;
let robj = results[Object.keys(results)[0]];
if (!robj || robj[Object.keys(robj)[0]] == null ) {
faddelem('p',document.body,{innerHTML:'No results returned.'});
return false;
};
let intdesc = l_date_field+' '+l_interval;
let t=0;
let m=0;
let ms='';
let data = [];
for (const property in robj) {
let c=robj[property];
t=t+c; // total count
m=c>m?c:m; // max count
data.push({interval:property,count:c});
};
faddelem('p',document.body,{innerHTML:'total records: '+fcomnum(xobj.total_results)+' '
+'[<span id="export"><a>export</a></span>]<br />'
+'total observation count: '+fcomnum(t)+'<br />'
+intdesc.toLowerCase()+' max count: '+fcomnum(m)+'<br />'
+'max '+ intdesc.toLowerCase()+': <span id="maxint"></span>'
});
document.getElementById('export').onclick = function() { fexport(data); };
fvisualize(data); // add chart
//table headers
let table = faddelem('table',document.body,{id:'main'});
let thead = faddelem('thead',table);
let hrow = faddelem('tr',thead);
let labels = [
{innerText:'#'},
{innerText:l_date_field+' '+l_interval},
{classList:'tar',innerText:'Count'},
{classList:'tar',innerText:'% of Total'},
{classList:'tar',innerText:'% of Max'},
];
faddelems('th',hrow,labels);
//table rows
let tbody = faddelem('tbody',table);
for (i=0;i<data.length;i++) {
let c = data[i].count;
let int = data[i].interval;
ms=c<m?ms:(ms===''?int:ms+', '+int); // max day(s)
let brow = faddelem('tr',tbody);
let values = [
{innerText:i+1},
{innerText:int},
{classList:'tar',innerText:fcomnum(c)},
{classList:'tar',innerText:fpct(c/t,2)},
{classList:'tar',innerText:fpct(c/m)},
];
faddelems('td',brow,values);
};
//table footers
let tfoot = faddelem('tfoot',table);
let frow = faddelem('tr',tfoot);
let values = [
{innerText:'Total'},
{innerText:''},
{classList:'tar',innerText:fcomnum(t)},
{classList:'tar',innerText:fpct(t/t,2)},
{classList:'tar',innerText:''},
];
faddelems('td',frow,values);
document.getElementById('maxint').innerHTML=ms;
};
function fvisualize(data) { //adapted from https://observablehq.com/@d3/zoomable-bar-chart
let rotatex = (!p_interval || p_interval==='month_of_year' || data.length<=8)?false:true;
let maxcount = d3.max(data, d => d.count);
let margin = ({top:5, right:0, bottom:(rotatex?70:30), left:(maxcount>=900000?56:maxcount>=900?48:32)});
let width = window.innerWidth*0.8;
let height = 200;
//let height = width/3;
//height = (height<200)?200:(height>300)?300:height;
let maxzoom = Math.ceil(data.length/15);
let x = d3.scaleBand()
.domain(data.map(d => d.interval))
.range([margin.left, width - margin.right])
.padding(0.1);
let y = d3.scaleLinear()
.domain([0, maxcount]).nice()
.range([height - margin.bottom, margin.top]);
let xAxis = g=> {
g.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0));
if (rotatex) {
g.selectAll("text")
.style("text-anchor","end")
.attr("dx","-.8em")
.attr("dy",".15em")
.attr("transform", "rotate(-65)");
};
};
let yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y));
//.call(g => g.select(".domain").remove());
const svg = d3.select("body")
.append("svg")
.attr("viewBox", [0, 0, width, height])
.call(zoom);
svg.append("g")
.attr("class","bars")
.attr("fill","gray")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => x(d.interval))
.attr("y", d => y(d.count))
.attr("height", d => y(0) - y(d.count))
.attr("width", x.bandwidth());
svg.append("g")
.attr("class", "x-axis")
.call(xAxis);
svg.append("g")
.attr("class", "y-axis")
.call(yAxis);
return svg.node();
function zoom(svg) {
const extent = [[margin.left, margin.top], [width - margin.right, height - margin.top]];
svg.call(d3.zoom()
.scaleExtent([1,maxzoom])
.translateExtent(extent)
.extent(extent)
.on("zoom", zoomed));
function zoomed() {
x.range([margin.left, width - margin.right].map(d => d3.event.transform.applyX(d)));
svg.selectAll(".bars rect").attr("x", d => x(d.interval)).attr("width", x.bandwidth());
svg.selectAll(".x-axis").call(xAxis);
};
};
};
function fexport(data) {
let ebutton = document.getElementById('export');
ebutton.innerHTML = 'exporting...';
let ary = [[
l_date_field+' '+l_interval,
'Observation Count',
]];
for (let row of data) {
ary.push([
row.interval,
row.count,
]);
};
// transfer the contents of the array into a data object, create a hyperlink to the object, and simulate a click on the hyperlink to download the object.
let csv = 'data:text/csv;charset=utf-8,'+ ary.map(e => e.join(',')).join('\n');
let euri = encodeURI(csv);
let link = document.createElement('a');
link.href = euri;
link.download = 'inat_obs_histogram.csv';
document.body.appendChild(link); // for FF
link.click();
ebutton.innerHTML = 'exported';
};
let apibase = 'https://api.inaturalist.org/v1/observations/histogram';
let apiurl = apibase+((winurlparams!='')?('?'+winurlparams):'');
let apirefurl = 'https://api.inaturalist.org/v1/docs/#!/Observations/get_observations_histogram';
let apirefname = 'iNaturalist Observation Histogram';
let apiref = furl(apirefurl,apirefname);
faddelem('h1',document.body,{innerText:'iNaturalist Observation Count by '+l_date_field+' '+l_interval});
if (winurlsearchstr==='') {
let instructions = [
{innerHTML:'This page will present results from the '+apiref+' API endpoint in a friendly format. It also visualizes the data in a bar chart (using D3.js) that is zoomable along the X axis (in cases where there are more than 15 ticks). This page requires that you append some parameters to your URL.'},
{innerHTML:'Suppose the address of this page is '+winurlexsearchstr+', <br />and you want to see the results of '+furl(famp(apibase+'?interval=day&d1=2010-01-01&user_id=bob'))+' in a friendly format, <br />then you would open '+furl(famp(winurlexsearchstr+'?interval=day&d1=2010-01-01&user_id=bob'))+' in your browser.'},
{innerHTML:"Note that if you use interval=day and date_field=observed, you can set a beginning date (ex. d1=2010-01-01) to pull back more than just the last year's observed days.<br />Similarly, if you use interval=day and date_field=created, you can set a beginning date (created_d1) to pull back more than just the last year's created days."},
];
faddelems('p',document.body,instructions);
}
else {
faddelem('p',document.body,{innerHTML:'This is the base query: '+furl(famp(apiurl))+'. (This page will accept most parameters from the '+apiref+' API endpoint.)'});
fetch(apiurl)
.then((response) => {
if (!response.ok) { throw new Error(response.status+' ('+response.statusText+') returned from '+response.url); };
return response.json();
})
.then((data) => { fresults(data); })
.catch((err) => {
console.error(err.message);
faddelem('p',document.body,{innerText:'There was a problem retrieving data. Error '+err.message+'.'});
});
};
</script>
</body>
</html>