Tooltip with Multi-Series Line Chart in Vega-Lite API - d3.js

I am trying to recreate this example in Vega-Lite API in an Observable notebook. I am able to recreate the ruler with the multiple line series from another example in Observable. But I am having trouble adding tooltips, I would like to add the symbol ticker and the price of the stock. Here is my Observable notebook. Where would I put the tooltip specifications? Thanks!
plot = {
// select a point for which to provide details-on-demand
const hover = vl.selectSingle()
.encodings('x') // limit selection to x-axis value
.on('mouseover') // select on mouseover events
.nearest(true) // select data point nearest the cursor
.empty('none'); // empty selection includes no data points
// define our base line chart
const line = vl.markLine()
.data(stocks)
.encode(
vl.x().fieldT('date'),
vl.y().fieldQ('price'),
vl.color().fieldN('symbol'),
);
// shared base for new layers, filtered to hover selection
const base = line.transform(vl.filter(hover));
return vl.data(stocks)
.layer(
line,
// add a rule mark to serve as a guide line
vl.markRule({color:'#c0c0c0'})
.transform(
vl.filter(hover),
vl.pivot({pivot: 'symbol', value: 'price', groupby: ['date']}))
.encode(vl.x().fieldT('date'),
vl.tooltip().fieldQ('price')),
// add circle marks for selected time points, hide unselected points
line.markCircle()
.select(hover) // use as anchor points for selection
.encode(vl.opacity().if(hover, vl.value(1)).value(0),
vl.tooltip(['symbol','price']))
)
.render(); }

Here's how you use pivot on that example
vl.pivot('symbol').value('price').groupby( ['date']))
The pivot there helps you getting the data into table format, so you can have all the symbol prices available in one row. Here is a full working example of a Vega-Lite API multi-line series chart with tooltips:
https://observablehq.com/#vega/multi-series-line-chart-with-tooltip

Related

amCharts 4 - How to Access Currently-Hovered Series Data/Color in XYChart in JavaScript

I'm trying to access the currently-hovered series data and color via JavaScript. The data is available to the legend and tooltip, but I'm not sure how to directly access it.
It's possible to place the legend in an external container, but their code creates a lot of additional containers/wrappers which makes formatting difficult. This Github question addresses it, but no answer was provided.
Perhaps events could be used to detect changes in the legend text or tspan elements and then grab the new text, but I'm not sure how to do this (using amCharts events) and how efficient it would be (especially with multiple series and/or charts with synced cursors).
Another idea was to get the data based on cursor position, but this seems inefficient (cursorpositionchanged fires too often - on mouse/cursor movement even when the series data hasn't changed). Maybe it could be done more efficiently based on change in dateAxis value? For example, using the positionchanged event listener:
chart.cursor.lineX.events.on('positionchanged', function() {
// get series data and do something with it
});
At least when using chart.cursor.xAxis = dateAxis, the positionchanged event only seems to fire when the cursor jumps to a new value. So it would be more efficient than an event that fired on mouse/cursor movement.
Any suggestions would be appreciated.
UPDATE
By currently-hovered, I am referring to the series data and color accessible via the tooltip (for example) with the mouse over the chart.
Examples: CandlestickSeries and LineSeries
One method you can try is to set an adapter for tooltipText on the object of concern. Since this may run multiple times especially via a chart cursor, perhaps keep track of changes to the tooltip via monitoring the unique value, e.g. in the samples provided that would be the date field. The data you're looking for can be found in the adapter's target.tooltipDataItem. The color, if on the series, will be target.tooltipDataItem.component.fill (in the case of the line series example, the target is the line series and has no change of color, so you can just use target.fill), otherwise e.g. in the case of CandleStick series the color would be on the candle stick, or column, i.e. via target.tooltipDataItem.column.fill.
Sample adapter for LineSeries:
var tooltipDate;
series.adapter.add("tooltipText", function(text, target) {
// data via target.tooltipDataItem.dataContext
console.log('text adapter; color: ', target.tooltipDataItem.component.fill.hex);
if (tooltipDate !== target.tooltipDataItem.dataContext.date) {
console.log('new tooltip date, do something');
tooltipDate = target.tooltipDataItem.dataContext.date;
}
// note: in this case: component === target
return text;
});
Demo:
https://codepen.io/team/amcharts/pen/9f621f6a0e5d0441fe55b99a25094e2b
Sample Candlestick series adapter:
var tooltipDate;
series.adapter.add("tooltipText", function(text, target) {
// data via target.tooltipDataItem.dataContext
console.log('text adapter; color: ', target.tooltipDataItem.column.fill.hex);
if (tooltipDate !== target.tooltipDataItem.dataContext.date) {
console.log('new tooltip date, do something');
tooltipDate = target.tooltipDataItem.dataContext.date;
}
return text;
});
Demo:
https://codepen.io/team/amcharts/pen/80343b59241b72cf8246c266d70281a7
Let us know if this is making sense, and if the adapter route is a good point in time to capture changes, data, color, as well as if it's efficient enough a manner to go about this.

Is there a way to filter a dimension based on the value of another field?

I'm building a data dashboard for a project and I want to be able to compare data from two distinct groups in the same dataset.
My dataset looks like this:
Number,Name,Gender,Race,Height,Publisher,Alignment,Weight,Superpower,Strength,Costume Colour
1,A-Bomb,Male,Metahuman,203,Marvel Comics,Good,441,Superhuman Strength,10,None
2,Abin Sur,Male,Alien,185,DC Comics,Good,90,Cosmic Power,40,Green
3,Abomination,Male,Metahuman,203,Marvel Comics,Bad,441,Superhuman Strength,10,None
4,Abraxas,Male,Cosmic Entity,1000,Marvel Comics,Bad,1000,Reality Warping,40,Green
5,Absorbing Man,Male,Metahuman,193,Marvel Comics,Bad,122,Matter Duplication,5,None
6,Adam Strange,Male,Human,185,DC Comics,Good,88,None,0,Red
I want to create two separate selectMenus which list the character names, but with each of the two menus filtered on Publisher name.
So one drop down will have all the characters associated with Marvel Comics, and the other will have all the characters associated with DC Comics.
Once this is set up, the idea is that the dashboard can then show a set of graphs which work as a comparison between the two characters that have been selected - so I don't want the entire dataset to be split out, I just want the selection to be filtered by Publisher.
I've been through dozens of different Stack Overflow threads about similar stuff but still struggling. I've created the dimensions for character name and character publisher but I'm getting really lost trying to use one to filter the other.
This is what I've got so far (ignore the costume color stuff, that's for something further down the line) - the data in 'heroes-information.csv' is in the same format I shared above.
// Bring in data from csv files
Promise.all([d3.csv("../data/heroes-information.csv"), d3.csv("../data/costume-colors.csv")])
.then(function(data) {
// Tidy data before use
data.forEach(function(d) {
d.Height = +d.Height;
d.Weight = +d.Weight;
d.Strength = +d.Strength;
});
// Bring in Heroes data
var ndx = crossfilter(data[0]);
// Bring in costume color data
var ndxcol = crossfilter(data[1]);
// Create colorScale to dynamically color pie chat slices
var colorScale = d3.scaleOrdinal()
.domain(data[1].map(row => row.Name))
.range(data[1].map(row => row.RGB));
// Define chart type
var dccomicsSelector = dc.selectMenu('#dccomics-selector');
// Define chart dimension
var character = ndx.dimension(dc.pluck('Name'));
var characterPublisher = ndx.dimension(dc.pluck('Publisher'));
var dccomicsCharacters = character.group();
var dccomicsPublisher = characterPublisher.group();
dccomicsSelector
.dimension(character)
.group(dccomicsCharacters);
dc.renderAll();
});
I'm probably missing something really obvious but I'm fairly new to DC.js and Crossfilter so a bit lost in the weeds with this one, any help would be much appreciated!

Adjusting small multiples sparklines

I have an heatmap that show some data and a sparkline for each line of the heatmap.
If the user click on a row label, then the data are ordered in decreasing order, so each rect is placed in the right position.
Viceversa, if the user click on a column label.
Each react is placed in the right way but I'm not able to place the sparkline.
Here the code.
When the user click on a row label, also the path inside the svg containing the sparkline should be updated.
And then, when the user click on a column label, the svg containing the sparkline should be placed in the correct line.
To place the svg in the right place, I try to use the x and y attributes of svg. They are updated but the svg doesn't change its position. Why?
Here is a piece of code related to that:
var t = svg.transition().duration(1000);
var values = [];
var sorted;
sorted = d3.range(numRegions).sort(function(a, b) {
if(sortOrder) {
return values[b] - values[a];
}
else {
return values[a] - values[b];
}
});
t.selectAll('.rowLabel')
.attr('y', function(d, k) {
return sorted.indexOf(k) * cellSize;
});
Also, I don't know how to change the path of every sparkline svg. I could take the data and order them manually, but this is only good for the row on which the user has clicked and not for all the others.
How can I do?
The vertical and horizontal re-positioning/redrawing of those sparklines require different approaches:
Vertical adjustment
For this solution I'm using selection.sort, which:
Returns a new selection that contains a copy of each group in this selection sorted according to the compare function. After sorting, re-inserts elements to match the resulting order.
So, first, we set our selection:
var sortedSVG = d3.selectAll(".data-svg")
Then, since selection.sort deals with data, we bind the datum, which is the index of the SVG regarding your sorted array:
.datum(function(d){
return sorted.indexOf(+this.dataset.r)
})
Finally, we compare them in ascending order:
.sort(function(a,b){
return d3.ascending(a,b)
});
Have in mind that the change is immediate, not a slow and nice transition. This is because the elements are re-positioned in the DOM, and the new structure is painted immediately. For having a slow transition, you'll have to deal with HTML and CSS inside the container div (which may be worth a new specific question).
Horizontal adjustment
The issue here is getting all the relevant data from the selection:
var sel = d3.selectAll('rect[data-r=\'' + k + '\']')
.each(function() {
arr.push({value:+d3.select(this).attr('data-value'),
pos: +d3.select(this).attr('data-c')});
});
And sorting it according to data-c. After that, we map the result to a simple array:
var result = arr.sort(function(a,b){
return sorted.indexOf(a.pos) - sorted.indexOf(b.pos)
}).map(function(d){
return d.value
});
Conclusion
Here is the updated Plunker: http://next.plnkr.co/edit/85fIXWxmX0l42cHx or http://plnkr.co/edit/85fIXWxmX0l42cHx
PS: You'll need to re-position the circles as well.

click in datatable to filter other charts (dc.js)

I need to filter other charts when I click a row in the datatable.
I did
my_table.on('pretransition', function (table) {
table.selectAll('td.dc-table-column')
.on('click',function(d){
table.filter(d.key)
dc.redrawAll();
})
});
but nothing happens in the other charts.
Can you help me, please?
If the table dimension is a dimension...
The data that ordinarily populates a data table is the raw rows from the original data set, not key/value pairs.
So it is likely that d.key is undefined.
I'd advise you first to stick
console.log(d)
into your click handler to see what your data looks like, to make sure d.key is valid.
Second, remember that a chart filters through its dimension. So you will need to pass a value to table.filter() that is a valid key for your dimension, and then it will filter out all rows for which the key is different. This may not be just the one row that you chose.
Typically a table dimension is chosen for the way it orders the values for the rows. You might actually want to filter some other dimension. But hopefully this is enough to get you started.
But what if the the table dimension is a group?
The above technique will only work if your table takes a crossfilter dimension as its dimension. If, as in the fiddle you linked in the comments, you're using a group as your dimension, that object has no .filter() method, so the table.filter() method won't do anything.
If you only need to filter the one item that was clicked, you could just do
foodim.filter(d.key)
This has an effect but it's not that useful.
If you need the toggle functionality used in dc's ordinal charts, you'll need to simulate it. It's not all that complicated:
// global
var filterKeys = [];
// inside click event
if(filterKeys.indexOf(d.key)===-1)
filterKeys.push(d.key);
else
filterKeys = filterKeys.filter(k => k != d.key);
if(filterKeys.length === 0)
foodim.filter(null);
else
foodim.filterFunction(function(d) {
return filterKeys.indexOf(d) !== -1;
})
Example fiddle: https://jsfiddle.net/gordonwoodhull/kfmfkLj0/9/

In AmCharts, how can I pull the visible coordinates of the categoryAxis based on the scrollbar?

I have a an AmChart, JavaScript chart, column chart with scroll.
I'd like to be able to pull the category axis data for the min and the max values that are currently being displayed in the chart.
Example:
If I have 0-10 on the x-axis and I zoom to 4-6, I want to be able to reference the data on point 4 and point 6.
I am new to AmCharts so hopefully I am just missing something simple but I can't seem to figure this out.
Here is a link to a chart I made:
https://live.amcharts.com/U4YmV/
You can use the zoomed event to capture the startIndex and endIndex from its event object.
In the example below, zoomedData is the zoom selection.
chart.addListener("zoomed", zoomed);
function zoomed (e) {
var chart = e.chart,
data = chart.dataProvider,
zoomedData = data.slice(e.startIndex, e.endIndex + 1);
}
Please check the example here: https://codepen.io/team/amcharts/pen/246e8f826610e848b7389fb85657348a

Resources