Can I customize the tooltip text in a Google Geochart chart? - api

Below is the code I'm using, based on a how to I found in Google's documentation, but I'm not sure if it applies to the Geochart, if I'm doing it right, or if there is some other way to do it for a Geochart.
This code works fine if I don't include the tooltip column. When I do, I get the error "Incompatible data table: Error: Table contains more columns than expected (Expecting 2 columns)," displayed where the Geochart should be.
This question addresses the same issue, but not specifically for a Geochart.
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load( 'visualization', '1', { 'packages': ['geochart'] } );
google.setOnLoadCallback( drawRegionsMap );
function drawRegionsMap()
{
var data = google.visualization.arrayToDataTable([
[ 'State', 'Relevance', {type: 'string', role: 'tooltip'} ],
[ 'Alabama', 3, 'tooltip test text' ],
[ 'Arizona', 1, 'tooltip test text' ],
]);
var options =
{
region: 'US',
resolution: 'provinces',
};
var chart = new google.visualization.GeoChart( document.getElementById( 'chart_div' ) );
chart.draw( data, options );
};
</script>

I was able to include the text i wanted in the tooltip, including the values this way:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country'); // Implicit domain label col.
data.addColumn('number', 'Value'); // Implicit series 1 data col.
data.addColumn({type:'string', role:'tooltip'}); //
data.addRows([
[{v:"US",f:"United States of America"},1,"21% of Visits"],
[{v:"GB",f:"United Kingdom"},2,"7% of visits"],
[{v:"DE",f:"Germany"},3,"6% of visits"],
[{v:"FR",f:"France"},4,"5% of visits"],
[{v:"ES",f:"Spain"},5,"5% of visits"],
[{v:"CA",f:"Canada"},6,"4% of visits"],
[{v:"IT",f:"Italy"},7,"4% of visits"],
[{v:"NL",f:"The Netherlands"},8,"4% of visits"],
[{v:"BR",f:"Brazil"},9,"4% of visits"],
[{v:"TR",f:"Turkey"},10,"3% of visits"],
[{v:"IN",f:"India"},11,"3% of visits"],
[{v:"RU",f:"Russia"},12,"3% of visits"],
[{v:"AU",f:"Australia"},13,"2% of visits"],
]);
This way, for example "United States of America" would be line 1 of the tooltip, and "21% of visits" would be the second line. With this format I can include whatever text I want in the tooltip, in both lines.

In order to customize the tooltip to use html including new line / images please check this example:
http://jsfiddle.net/SD4KA/
google.load('visualization', '1.1', {packages: ['geochart'], callback: drawVisualization});
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Country', 'Value', {role: 'tooltip', p:{html:true}}],
['Russia', 5, 'Hello world<br>test'],
['US', 20, '<img src="https://www.google.com/images/srpr/logo6w.png"/>']]);
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
chart.draw(data, {
width: 800,
height: 600,
tooltip: {
isHtml: true
}
});
}
Since v1.1 geochart supports html for tooltips

There are three alternatives presented in this thread
Set the formatted value of your data points manually (using the #setFormattedValue() DataTable method)
Use one of the formatters on a DataTable column
Include a 'tooltip' role column in the DataTable
I've personally used first one, and with your example should be like
var data = google.visualization.arrayToDataTable([
[ 'State', 'Relevance' ],
[ 'Alabama', { v: 3, f: 'tooltip test text' } ],
[ 'Arizona', { v: 1, f: 'tooltip test text' } ],
]);

I ran into a similar issue for a scatter chart. I had to use arrayToDataTable to get the data into the chart as opposed to DataTable() and addColumn() as suggested in other answers.
In order to get it to work, you make the call to arrrayToDataTable() as you are currently doing and saving to the variable data.
Then, you need to specify which column you want to be treated as a tooltip (and you must specify which columns should be plotted as well). In the following example, columns 0 and 1 contain the plot data, and column 2 contains the tooltip strings.
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {sourceColumn: 2,role:'tooltip'}]);
Finally, you must make the call to draw with the view variable rather than with the data variable:
chart.draw(view, options);

It seems like it is impossible to format the text the exact way I was attempting to with the GeoChart tool. Below is the solution I finally came up with and the rendered map:
Rendered Map with Tooltip View
PHP & JavaScript Code
<!-- generate geo map -->
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load( 'visualization', '1', { 'packages': ['geochart'] } );
google.setOnLoadCallback( drawRegionsMap );
function drawRegionsMap()
{
// create data table
var data = google.visualization.arrayToDataTable([
<?php echo $data_table; ?>
]);
// create chart object
var chart = new google.visualization.GeoChart(
document.getElementById( 'chart_div' )
);
// defines the data for the tooltip
var formatter = new google.visualization.PatternFormat('{0}');
formatter.format( data, [0,1], 1 );
var formatter = new google.visualization.PatternFormat('{2}');
formatter.format( data, [0,1,2], 0 );
// defines the data for the chart values
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
// set options for this chart
var options =
{
width: <?php echo $width; ?>,
region: 'US',
resolution: 'provinces',
colorAxis: { colors: ['#abdfab', '#006600'] },
legend: 'none'
};
// draw chart
chart.draw( view, options );
};
</script>
<div id="chart_div" style="width: <?php echo $width; ?>px; height: <?php echo $height; ?>px;"></div>
Rendered HTML
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load( 'visualization', '1', { 'packages': ['geochart'] } );
google.setOnLoadCallback( drawRegionsMap );
function drawRegionsMap()
{
// create data table
var data = google.visualization.arrayToDataTable([
[ 'State', 'in', 'String' ],
[ 'Arizona', 2, 'Has Facility, Sells Direct' ],
[ 'California', 4, 'Has Facility, Has Distributor, Sells Direct' ],
[ 'Colorado', 1, 'Sells Direct' ],
[ 'Florida', 1, 'Has Distributor' ],
[ 'Georgia', 1, 'Has Distributor' ],
[ 'Idaho', 1, 'Sells Direct' ],
[ 'Illinois', 1, 'Has Distributor' ],
[ 'Indiana', 1, 'Has Distributor' ],
[ 'Iowa', 1, 'Has Distributor' ],
[ 'Kansas', 1, 'Has Distributor' ],
[ 'Kentucky', 1, 'Has Distributor' ],
[ 'Louisiana', 1, 'Has Distributor' ],
[ 'Maryland', 2, 'Has Distributor' ],
[ 'Montana', 1, 'Sells Direct' ],
[ 'Nevada', 2, 'Has Facility, Sells Direct' ],
[ 'New Mexico', 2, 'Has Facility, Sells Direct' ],
[ 'North Carolina', 1, 'Has Distributor' ],
[ 'North Dakota', 1, 'Has Distributor' ],
[ 'Oklahoma', 1, 'Sells Direct' ],
[ 'Oregon', 1, 'Sells Direct' ],
[ 'Pennsylvania', 1, 'Has Distributor' ],
[ 'South Carolina', 1, 'Has Distributor' ],
[ 'Tennessee', 1, 'Has Distributor' ],
[ 'Texas', 1, 'Has Distributor' ],
[ 'Utah', 2, 'Has Facility, Sells Direct' ],
[ 'Washington', 1, 'Sells Direct' ],
[ 'Wyoming', 1, 'Sells Direct' ], ]);
// create chart object
var chart = new google.visualization.GeoChart(
document.getElementById( 'chart_div' )
);
// defines the data for the tooltip
var formatter = new google.visualization.PatternFormat('{0}');
formatter.format( data, [0,1], 1 );
var formatter = new google.visualization.PatternFormat('{2}');
formatter.format( data, [0,1,2], 0 );
// defines the data for the chart values
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
// set options for this chart
var options =
{
width: 286,
region: 'US',
resolution: 'provinces',
colorAxis: { colors: ['#abdfab', '#006600'] },
legend: 'none'
};
// draw chart
chart.draw( view, options );
};
</script>
<div id="chart_div" style="width: 286px; height: 180px;"></div>

Related

Ramda - how to use multiple functions on the same data structure

I am trying to use multiple ramda functions on this example:
const data = {
"tableItems": [
{
"id": 1,
"name": "1",
"startingPoint": true,
"pageNumber": 15,
"nodes": [
100,
200
]
},
{
"id": 2,
"name": "2",
"startingPoint": true,
"pageNumber": 14,
"nodes": [
300,
400
]
}
],
"nodes": [
{
"id": 100,
"tableItemId": 1,
"content": "test"
},
{
"id": 200,
"tableItemId": 1,
"content": "test"
},
{
"id": 300,
"tableItemId": 2,
"content": "test"
},
{
"id": 400,
"tableItemId": 2,
"content": "test"
}
]
}
I am trying to create new JSON which should look like this where nodes array should be filled with another ramda function:
const newJSON = [
{
"id": "chapter-1",
"name": "2",
"nodes": []
},
{
"id": "chapter-2",
"name": "1",
"nodes": []
}
]
I started with:
let chapters = [];
let chapter;
const getChapters = R.pipe(
R.path(['tableItems']),
R.sortBy(R.prop('pageNumber')),
R.map((tableItem) => {
if(tableItem.startingPoint) {
chapter = {
id: `chapter-${chapters.length+1}`,
name: tableItem.name,
nodes: []
}
chapters.push(chapter);
}
return tableItem
})
)
But how to combine getNodes which needs access to the whole scope of data?
I tried pipe but something is not working.
Example:
const getNodes = R.pipe(
R.path(['nodes']),
R.map((node) => {
console.log(node)
})
)
R.pipe(
getChapters,
getNodes
)(data)
Any help would be appreciated.
We could write something like this, using Ramda:
const {pipe, sortBy, prop, filter, map, applySpec, identity, propEq, find, __, addIndex, assoc} = R
const transform = ({tableItems, nodes}) => pipe (
filter (prop ('startingPoint')),
sortBy (prop ('pageNumber')),
map (applySpec ({
name: prop('name'),
nodes: pipe (prop('nodes'), map (pipe (propEq ('id'), find (__, nodes))), filter (Boolean))
})),
addIndex (map) ((o, i) => assoc ('id', `chapter-${i + 1}`, o))
) (tableItems)
const data = {tableItems: [{id: 1, name: "1", startingPoint: true, pageNumber: 15, nodes: [100, 200]}, {id: 2, name: "2", startingPoint: true, pageNumber: 14, nodes: [300, 400]}], nodes: [{id: 100, tableItemId: 1, content: "test"}, {id: 200, tableItemId: 1, content: "test"}, {id: 300, tableItemId: 2, content: "test"}, {id: 400, tableItemId: 2, content: "test"}]}
console .log (transform (data))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
First we filter the tableItems to include only those with startingPoint of true, then we sort the result by pageNumber. Then for each, we create name and nodes elements, based on the original data and on a function that maps the node values to the element in the initial nodes property. Finally, for each one, we add the chapter-# id element using addIndex (map).
This works, and is not horrible. It would take a fair bit of work to make this entirely point-free, I believe. And I don't find it worthwhile... especially because this Ramda version doesn't add anything to a simpler vanilla implementation:
const transform = ({tableItems, nodes}) =>
tableItems
.filter (x => x .startingPoint)
.sort (({pageNumber: a}, {pageNumber: b}) => a - b)
.map (({name, nodes: ns}, i) => ({
id: `chapter-${i + 1}`,
name,
nodes: ns .map (n => nodes .find (node => node .id == n)) .filter (Boolean)
}))
const data = {tableItems: [{id: 1, name: "1", startingPoint: true, pageNumber: 15, nodes: [100, 200]}, {id: 2, name: "2", startingPoint: true, pageNumber: 14, nodes: [300, 400]}], nodes: [{id: 100, tableItemId: 1, content: "test"}, {id: 200, tableItemId: 1, content: "test"}, {id: 300, tableItemId: 2, content: "test"}, {id: 400, tableItemId: 2, content: "test"}]}
console .log (transform (data))
.as-console-wrapper {max-height: 100% !important; top: 0}
This works similarly to the above except that it assigns the id at the same time as name and nodes.
I'm a founder of Ramda and remain a big fan. But it doesn't always add anything to vanilla modern JS.
You can use a curried function. Because the pipe will always pipe the result of the previous function call into the next function. You can use R.tap if you want to step over.
However, I guess you want to have the data object and the output of the previous function call both in your getNodes function. In that case you can use a curried function, where you pass the response of the previous function as last parameter.
const getNodes = R.curryN(2, function(data, tableItemList){
console.log(tableItemList) // result of previous function call
return R.pipe(
R.path(['nodes']),
R.map((node) => {
console.log('node:', node);
})
)(data)
})
And use it like:
R.pipe(
getChapters,
getNodes(data)
)(data)
I would split the solution into two steps:
Prepare the tableItems and nodes to the required end state using R.evolve - filter, sort, and then use R.toPairs the tableItems to get an array that includes the index and the object. Group the nodes by id so you can pick the relevant nodes by id in the combine step.
Combine both properties to create the end result by mapping the new tableItems, and using R.applySpec to create the properties.
const {pipe, evolve, filter, prop, sortBy, toPairs, groupBy, map, applySpec, path, flip, pick} = R
const transform = pipe(
evolve({ // prepare
tableItems: pipe(
filter(prop('startingPoint')),
sortBy(prop('pageNumber')),
toPairs
),
nodes: groupBy(prop('id'))
}),
({ tableItems, nodes }) => // combine
map(applySpec({
id: ([i]) => `chapter-${+i + 1}`,
name: path([1, 'name']),
nodes: pipe(path([1, 'nodes']), flip(pick)(nodes)),
}))(tableItems)
)
const data = {tableItems: [{id: 1, name: "1", startingPoint: true, pageNumber: 15, nodes: [100, 200]}, {id: 2, name: "2", startingPoint: true, pageNumber: 14, nodes: [300, 400]}], nodes: [{id: 100, tableItemId: 1, content: "test"}, {id: 200, tableItemId: 1, content: "test"}, {id: 300, tableItemId: 2, content: "test"}, {id: 400, tableItemId: 2, content: "test"}]}
console.log(transform(data))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>

Apex Line Area chart is not getting displayed on the page in Vuejs

I am stuck on a page where i am not able to display the charts on the page.
To make it simplify what I have done is, here is the code sandbox:
I see there an error in console about the data, I am not sure about it.
https://codesandbox.io/s/compassionate-snyder-bckoq
I want to display the chart like this (as an example), but I am not able to display on the code sandbox
Please help.
The format of series is not aligned with ApexCharts.
You need to transform the data to match with ApexChart format.
Please see the changes in the codesandbox.
https://codesandbox.io/s/small-dew-eztod?file=/src/components/HelloWorld.vue
options: {
// X axis labels
xaxis: {
type: 'date',
categories: ["2021-05-04", "2021-05-05", "2021-05-07"]
},
},
series: [
{
name: "total",
data: [2, 2, 1],
},
{
name: "pending",
data: [0, 1, 0],
},
{
name: "approved",
data: [2, 1, 1],
},
{
name: "rejected",
data: [0, 0, 0],
},
],
Transform data to fit ApexChart
const data = {
"2021-05-04": {
total: 2,
pending: 0,
approved: 2,
rejected: 0,
},
"2021-05-05": {
total: 2,
pending: 1,
approved: 1,
rejected: 0,
},
"2021-05-07": {
total: 1,
pending: 0,
approved: 1,
rejected: 0,
},
};
const xaxis = {
type: "date",
categories: Object.keys(data).map((key) => key), // ['2021-05-04', '2021-05-05', '2021-05-07']
};
let statusObj = [];
for (const dataValue of Object.values(data)) { // get the values from keys '2021-05-04', '2021-05-05' ...
// loop the values, e.g. 1st loop: { total: 2, pending: 0, approved: 2, rejected: 0, }
for (const [key, value] of Object.entries(dataValue)) {
// take 'total' as example, find if statusObj already has { name: 'total', data: [x] }, e.g. statusObj = { name: 'total', data: [1] }
const existingStatusIndex = Object.keys(statusObj).find(
(sKey) => statusObj[sKey].name === key
);
// if yes, return the index of it
if (existingStatusIndex) {
// add new data value to existing data object. e.g. { name: 'total', data: [1, 2] }
statusObj[existingStatusIndex].data.push(value);
continue;
}
// if no, create a new object and add it to statusObj
statusObj.push({
name: key,
data: [value],
});
}
}
Output:
xaxis {
type: 'date',
categories: [ '2021-05-04', '2021-05-05', '2021-05-07' ]
}
statusObj [
{ name: 'total', data: [ 2, 2, 1 ] },
{ name: 'pending', data: [ 0, 1, 0 ] },
{ name: 'approved', data: [ 2, 1, 1 ] },
{ name: 'rejected', data: [ 0, 0, 0 ] }
]

Datatables custom filtering with server side

I'm using DataTables and also using server side processing (Django).
I have a seperate textfield in which I use it to custom filter data in the DataTable after the table has been rendered already.
The following works just fine (I want to custom filter columns):
var table = $('#problem_history').DataTable( {
"bJQueryUI": true,
"aaSorting": [[ 1, "desc" ]],
"aoColumns": [
// various columns here
],
"processing": true,
"serverSide": true,
"ajax": {
"url": "/getdata",
"data": {
"friend_name": 'Robert'
}
}
} );
So on the page load (initial load of the DataTable) it filters for 'Robert' just fine. But now I want to programmatically change the data to filter for "friend_name" == "Sara"
I already tried the following, the filteredData has a correct filtered object but the table itself does not redraw with the new filter.
var filteredData = table.column( 4 ).data().filter(
function ( value, index ) {
return value == 'Sara' ? true : false;
}
);
table.draw();
I also tried this but no luck:
filteredData.draw();
How can I achieve this?
Thank you for your help.
Here is a very nice explanation on how to do it:
https://datatables.net/reference/option/ajax.data
I am currently using this code:
"ajax": {"url":"/someURL/Backend",
"data": function ( d ) {
return $.extend( {}, d, {
"parameterName": $('#fieldIDName').val(),
"parameterName2": $('#fieldIDName2').val()
} );
}
}
You call it by doing the following:
$('#myselectid').change(function (e) {
table.draw();
});
If you want to submit by clicking on the button, change the .change to .click and make sure that ID is pointing to button's id in a HTML
You've almost got it. You just need to assign the filter var to
the data parameter that's passed in the datatables request:
"ajax": {
"url": "/getdata",
"data": {
"friend_name": $('#myselectid').val();
}
}
And to filter the data, just call draw() on the select change event
$('#myselectid').change(function (e) {
table.fnDraw();
});
For Basic searches, you should use the search() API:
// Invoke basic search for 'a'
dt.search('a', false)
For more complex queries, you can utilize searchBuilder backend by intercepting the ajax call through an open API. Here are some searchBuilder examples:
// Basic example:
// . (searchable_fields contains 'a'
// AND (office = Tokyo AND Salary > 100000)
// )
$('#problem_history').on('preXhr.dt', function(e, settings, data){
data['searchBuilder'] = {
'criteria': [
{'data': 'Office', 'origData': 'office', 'type': 'string'
,'condition': '='
,'value': ["Tokyo"], 'value1': "Tokyo"
}
,{'data': 'Salary', 'origData': 'salary', 'type': 'num'
,'condition': '>'
,'value': [100000], 'value1': 100000
}
]
,'logic': 'AND'
}
})
// Complex example:
// . (searchable_fields contains 'a'
// AND (
// (office = Tokyo AND Salary > 100000)
// OR (office = London AND Salary > 200000)
// )
// )
$('#problem_history').on('preXhr.dt', function(e, settings, data){
data['searchBuilder'] = {
'criteria': [
{'criteria': [
{'data': 'Office', 'origData': 'office', 'type': 'string'
,'condition': '='
,'value': ["Tokyo"], 'value1': "Tokyo"
}
,{'data': 'Salary', 'origData': 'salary', 'type': 'num'
,'condition': '>'
,'value': [100000], 'value1': 100000
}
]
,'logic': 'AND'
}
,{'criteria': [
{'data': 'Office', 'origData': 'office', 'type': 'string'
,'condition': '='
,'value': ["London"], 'value1': "London"
}
,{'data': 'Salary', 'origData': 'salary', 'type': 'num'
,'condition': '>'
,'value': [200000], 'value1': 200000
}
]
,'logic': 'AND'
}
]
,'logic': 'OR'
}
})
SearchBuilder Logic Types:
=
!=
contains
starts
ends
<
<=
>
>=
between
null
!null
SearchBuilder data value blocks:
value: [<val>] seems to always equal value1
value2: For upper bounds of 'between' logic where value1 would be lower bounds

Is it possible to add animations to dgrid rows?

We currently have a dgrid with a single column and rows like this:
Recently I added some code so that we can delete rows with the little X button that appears above the row when we hover them.
The handler calls this to delete the row:
this.grid.store.remove(rowId);
When we delete a row, since it's instantaneous and each row contains similar text, it's not always obvious to the user that something just happened.
I was wondering if it would be possible add some sort of dojo or css animation to the row deletion, like the deleted row fading or sliding out. This would make the row deletion more obvious.
Thanks
I have created a jsfiddle for animating(wipeOut) a selected row.
require({
packages: [
{
name: 'dgrid',
location: '//cdn.rawgit.com/SitePen/dgrid/v0.3.16'
},
{
name: 'xstyle',
location: '//cdn.rawgit.com/kriszyp/xstyle/v0.2.1'
},
{
name: 'put-selector',
location: '//cdn.rawgit.com/kriszyp/put-selector/v0.3.5'
}
]
}, [
'dojo/_base/declare',
'dgrid/OnDemandGrid',
'dgrid/Selection',
'dojo/store/Memory',
"dojo/fx",
'dojo/domReady!'
], function(declare, Grid, Selection, Memory,fx) {
var data = [
{ id: 1, name: 'Peter', age:24 },
{ id: 2, name: 'Paul', age: 30 },
{ id: 3, name: 'Mary', age:46 }
];
var store = new Memory({ data: data });
var options = {
columns: [
/*{ field: 'id', label: 'ID' },*/
{ field: 'name', label: 'Name' },
{ field: 'age', label: 'Age' }
],
store: store
};
var CustomGrid = declare([ Grid, Selection ]);
var grid = new CustomGrid(options, 'gridcontainer');
grid.on('dgrid-select', function (event) {
// Report the item from the selected row to the console.
console.log('Row selected: ', event.rows[0].data);
//WipeOut animation for selected row.
fx.wipeOut({ node: event.rows[0].element }).play();
});
});

Dojo Gridx with JsonStore

I'm trying to connect Gridx grid to JsonStore. The code and data is bellow. The problem is that Gridx is rendered correctly but it says: No items to display. Anybody know what I'm doing wrong? Dojo and Gridx are the latest versions installed with cpm.
edit: there is no ajax requet to /test/ in the Firebug/Chrom development tools
structure: [
{ field: 'id', name: 'Id' },
{ field: 'title', name: 'Title' },
{ field: 'artist', name: 'Artist' }
],
store: new JsonRestStore({
idAttribute: 'id',
target: '/test/'
}),
Data returned by /test is like this:
{
identifier: "id",
label: "title",
items: [
{
id: 1,
title: "Title 1",
artist: "Artist 1"
},
{
id: 2,
title: "Title 2",
artist: "Artist 2"
},
...
}
Grid is created with:
this.grid = new Grid({
structure: structure,
store: store,
modules: [
Pagination,
PaginationBar,
//Focus,
SingleSort,
ToolBar
],
//paginationInitialPage: 3,
paginationBarSizes: [10, 25, 50, 100],
paginationBarVisibleSteppers: 5,
paginationBarPosition: 'bottom'
}, this.gridNode);
have you specified which cache to use? In your case it should be an Async cache.
require([
'gridx/core/model/cache/Async',
.....
], function(Cache, ...){
this.grid = new Grid({
cacheClass: Cache,
......
});
I've found that this happens when the server doesn't return the Content-Range header in the response. Apparently the store isn't smart enough to just count the items in the returned array...