I'm using ChartJS to plot a dataset to a bar chart. When I hover over the bars the name of the series with values will appear, so far so good.
However in my application it's possible that I get back a single group (one serie) from my database call. When I hover over the single bar the name of the serie and value is missing.
Preferred output would be the same as image 1 with only the single serie displayed. How to achieve this?
code to watch for data and push to dataset for chart. No custom options are set.
$scope.$watch("obtainedVouchers|groupBy:'voucherTitle'", function(collection){
if (!_.isEmpty(collection)) {
$scope.voucherChart_data = [];
$scope.voucherChart_label = ["Ingeleverde vouchers"];
$scope.voucherChart_series = [];
$scope.voucherChart_colours = ["#43A7BF", "#5ADFFF", "#163840", "#2D6F7F", "#51C8E5"];
for (var key in collection) {
var x = collection[key].length;
$scope.voucherChart_series.push(key);
$scope.voucherChart_data.push([x]);
}
}
}, true);
Multiple serie chart
data collection
Single serie chart
data collection
Related
I am using amcharts 4 to display temperature lines. At times there are many stations so I would like to have just one tooltip and just for the value the cursor is at instead of one tooltip for every line (because then they overlap and some are unreadable).
And there might be several stations with the same temperature so I would have to list all of them in the tooltip.
Anyone knows how to achieve that?
In amcharts 3 I used a balloonFunction attached to the graphs to create my own tooltip. But yet I couldn't find how to do it with the series in amcharts 4.
Thanks for a hint!
So as David Liang mentioned, since all the data items converge along their x axis value (a datetime in this case), you can limit tooltips down to one by only setting one series' tooltipText, and it will have access to the rest of the data fields via data placeholders. E.g. even though series1's value field is E852_t4m, it can use series30's value by just putting "{median_tBel}".
But if you want to have a tooltip based on which line you're hovering over, how to do that depends whether or not you require the Chart Cursor.
If you don't need it, simply set the tooltipText on the line's bullets, e.g.
series1.bullets.getIndex(0).tooltipText = "{name} {valueY}°C";
Here's a demo of your fiddle with that:
https://codepen.io/team/amcharts/pen/803515896cf9df42310ecb7d8d7a2fb7
But if you require Chart Cursor, unfortunately there isn't a supported option at the moment. There's a kind of workaround but it's not the best experience. You start with doing the above. The Chart Cursor will trigger hover effects on all lines and their bullets, including triggering their tooltips. A bullet's tooltip is actually its series' (series1.bulletsContainer.children.getIndex(0).tooltip === series1.tooltip). If we remove the reference to the bullet's tooltip, e.g. series1.bullets.getIndex(0).tooltip = undefined;, the chart will check up the chain and refer to series' anyway. If we do the same to the series' tooltip, it'll go up the chain to chart.tooltip, if we do this to all series, we basically turn chart.tooltip into a singleton behavior of sorts. But it's not as responsive to mouseovers.
You'll see what I mean with this demo:
https://codepen.io/team/amcharts/pen/244ced223fe647ad6df889836da695a8
Oh, also in the above, you'll have to adjust the chart's tooltip to appear on the left/right of bullets with this:
chart.tooltip.pointerOrientation = "horizontal";
Edit:
Since the first method sufficed, I've updated it with an adapter that checks for other fields in range. In the adapter, the target will be the CircleBullet, target.dataItem.valueY is the currently hovered value, and target.dataItem.dataContext are the other fields at the same date.
This is how I modified tooltipText to show other series within +/-0.5C range of the currently-hovered bullet:
// Provide a range of values for determining what you'll consider to be an "overlap"
// (instead of checking neighboring x/y coords.)
function inRange(valueA, rangeA, rangeB) {
return valueA >= rangeA && valueA <= rangeB;
}
// Provide adapters for tooltipText so we can modify them on the fly
chart.series.each(function(series) {
series.bullets
.getIndex(0)
.adapter.add("tooltipText", function(tooltipText, target) {
// the other data fields will already match on the date/x axis, so skip
// the date and this bullet's data fields.
// (target.dataItem.component is the target's series.)
var skipFields = ["date", target.dataItem.component.dataFields.valueY];
// this bullet's value
var hoveredValue = target.dataItem.valueY;
// all the other data fields at this date
var data = target.dataItem.dataContext;
// flag for adding additional text before listing other nearby bullet values
var otherPoints = false;
Object.keys(target.dataItem.dataContext).forEach(function(field) {
// if the field is neither date, nor bullet's
if (!~skipFields.indexOf(field)) {
if (inRange(data[field], hoveredValue - 0.5, hoveredValue + 0.5)) {
if (!otherPoints) {
tooltipText += "\n\nOthers:";
otherPoints = true;
}
// Keep {data placeholder} notation to retain chart formatting features
tooltipText += "\n" + field + ": {" + field + "}°C";
}
}
});
return tooltipText;
});
});
If your series' data points have different x values, it's impossible to combine all the information into one tooltip.
But if they do have same x values, you can just turn on the tooltip for just one of the series:
...,
series: [{
type: "LineSeries",
tooltipHTML: `xxx`,
...
}, {
type: "LineSeries",
...
}, {
type: "LineSeries",
...
}],
...
And within the tooltip HTML, you have access to the data:
...,
tooltipHTML: `
<strong>Year: </strong>{year}<br />
<strong>Cars: </strong>{cars}<br />
<strong>Motorcycles: </strong>{motorcycles}<br />
<strong>Bicycles: </strong>{bicycles}
`,
...
demo: http://jsfiddle.net/davidliang2008/aq9Laaew/286519/
I have a population pyramid using the rCharts-highChart library implementation presented in here. I am trying to add a layer of bubble chart over the population pyramid. I have partial success in implementing it. The image below shows the chart I achieved.
enter image description here
I am not able to control some attributes of the bubble chart. I want datalabels to be displayed on the the bubble chart. However, the dataLabels are activated for the bar chart only. I want the dataLabels to be displayed on the bubble chart also. The code I use is below.
n1 <- hPlot(x = 'Agec',
y = 'Category',
type = 'bar',
group = 'HbA1c_levels',
plotBorderWidth = 1,
data = MyD.melt)
# Adding a series of bubble chart
n1$series(type = 'bubble',
data = (as.numeric(as.character(MyD$low)))
n1$series(type = 'bubble',
data = (as.numeric(as.character(MyD$high))))
n1$plotOptions(series = list(stacking = 'normal', pointPadding = 0, borderWidth = 0, dataLabels = list(enabled = TRUE)))
#dataLabels gets activated only for bar chart as shown in the figure
Further, the bubblechart is able to read the 'Y axis' when I specify a particular column from the dataframe as shown in the above code. I would want it to read the "X,Y,Z,name" attributes from a list or dataframe and then plot the bubbles. Any idea how it can be done?
In my HighCharts implementation I'm dynamically changing the data of all series of the chart. This all works as expected, but the legend gets refreshed each time aswell causing the filtered legend to become unfiltered.
Let me explain with the following example.
If you look at this sample by HighCharts themselves you will see the legend showing 'John', 'Jane' and 'Joe' : http://www.highcharts.com/demo/column-stacked
If you click on John you'll only see the series of Jane and Joe. If you'd now refresh the underlieing series the legend will refresh and John his data will be visible again.
I need to prevent this from happening. Anybody got an idea on how I could do this?
FYI; I'm updating the data like this:
function updateSeries(data, chart, vm) {
for (var i = 0, len = chart.series.length; i < len; i++) {
chart.series[0].remove();
}
var series = calculateSeries(data, vm);
_.each(series, function (serie) {
chart.addSeries(serie, false);
});
chart.redraw();
}
I'm aware that I'm actually removing and re-adding the series, but that's because I'm unsure of how to do this otherwise.
I am attempting to create a bar graph that when independent sliders are moved they change two bar graph svg heights at the same time and they are stacked, they are different colors show it shows two separate values in the same graph, basically showing growth vs the current. I am using jquery-ui and D3.js. Currently it only moves the one svg elements instead of both at the same time, Id like them both to move at the same time.
HTML
<div id="slider" class="slider">
<label for="amount">Age</label>
<input type="text" id="amount1" style="border:0; font-weight:bold;">
</div>
<div id="slider1" class="slider">
<label for="amount2">Retirement Age</label>
<input type="text" id="amount2" style="border:0; font-weight:bold;">
</div>
JS
//initialize sliders
jQuery(document).ready(function($) {
$("#slider").slider({
max: 100
});
$("#slider").slider({
min: 18
});
$("#slider1").slider({
max: 100
});
$("#slider1").slider({
min: 18
});
//slider actions
$("#slider, #slider1").slider({
value: 10,
animate: "fast" ,
slide: function (event, ui) {
//capture the value of the specified slider
var selection = $("#slider").slider("value");
var selection1 = $("#slider1").slider("value");
//fill the input box with the slider value
$( "#amount1" ).val( selection );
$( "#amount2" ).val( selection1 );
//set width and height, actually I'm a little confused what this is for
var w = 200;
var h = 200;
//data arrays for svgs
var dataset = [];
var dataset1 = [];
//fill the data arrays with slider values
dataset.push(selection);
dataset.push(selection1 + selection);
//draw rectangle on the page
var rectangle = svg.selectAll("rect")
.classed("collapse", true)
.data(dataset);
**
THIS IS WHERE IT CONFUSES ME
**
//I draw the second rectangle here, however I choose the same svg element,
//Im not sure what other way to get it to appear in the same space but
//I am sure this is what is causing my issues
var rectangle1 = svg.selectAll("rect")
.classed("collapse", true)
.data(dataset1);
//not sure what this does
rectangle.enter().append("rect");
rectangle1.enter().append("rect");
rectangle.attr("width", 200).transition().attr("fill", "#A02222").attr("height", function (d) { console.log('d is ' + d);
return d;
}).attr("x", function (d) {
return 40; //I dont know why I return 40?
}).attr("y", function (d) {
return 40; //Same here dont know why I return 40?
});
rectangle1.attr("width", 200).transition().attr("height", function (d) { console.log('d is ' + d);
return d;
}).attr("x", function (d) {
return 40; //I dont know why I return 40?
}).attr("y", function (d) {
return 40; //Same here dont know why I return 40?
});
}
// slider actions ends here
});
//Create SVG element
var svg = d3.select(".svgContain").append("svg").attr("width", 125).attr("height", 300);
});
For starters, you may want to follow this tutorial: http://bl.ocks.org/mbostock/3886208
The "return 40;" that you are wondering about are actually what will specify the position and dimensions of the rect's you're appending to the svg. Those shouldn't just be 40, they should be bound to values in the data set, or based on the index of the bar's series in the set of series or something more meaningful than 40.
There is a stacked bar chart data processor that will take a set of series and spit out a new set of series coordinate definitions that make it easier to calculate how rect's will stack in svg coordinate space: https://github.com/mbostock/d3/wiki/Stack-Layout
Then, there's the more general issue of how to deal with these "nested" data sets where you have series, and in the series there are values and you don't want to have to manually track and select individual series. There are several ways to handle this sort of situation. If you know you will only ever have two series, and you really want fine-grained control over each independently, you could assign the top level object an id and then start the data join for each of the plots by selecting that top level object by id... eg:
var container1 = d3.select("#myContainer1);
container1.selectAll("rect").data(myData1).append("rect");
var container2 = d3.select("#myContainer2);
container2.selectAll("rect").data(myData2).append("rect");
If you do something like that, the first select basically sets the context of the subsequent selects. So, only the rects inside of the "#myContainer1" or "#myContainer2" will get selected by each "selectAll" based on which context you're in.
The other approach is to use nested selections. Nested selections are a little more complicated to wrap your head around, but 90% of the time, this is the approach I use. With nested selections, you would restructure your data slightly and then apply nested selects/joins to bind each series to a dom element and then the values of each series to subelements of each of the series dom elements.
First, read this: http://bost.ocks.org/mike/nest/
and then try making your data something more like this:
data = [
{ key: "series1", values: [...]},
{ key: "series2", values: [...]}
];
Then, you will want to do a nested selection where you start with a selection of the "data" array and bind it to whatever svg or html element you have that wraps each of the two series.
var series = d3.select("svg").selectAll("g.series")
.data(data, function(d){return d.key; });
series.enter().append("g").attr("class", "series");
At this point, d3 will have added a "g" element to your svg element for each series and bound the series object (including the key and values array) to the appended elements. Next, you can make a nested selection to add series-specific elements to the g element... ie:
var rect = series.selectAll("rect").data(function(d) { return d.values });
rect.enter().append("rect");
Note that we used a function in our ".data(...)" call. That's because the values we want passed to the join actually depend on which specific series is being processed by D3.
Now, you'd have a rect added to the g element for each value in each series. Since you used d3 to do the data binding and you used the key function in the first select (".data(data, function(d){return d.key;}"), future selects done in the same nested/keyed manner will update the right g and rect elements.
Here's a Fiddle that demonstrates the concept:
http://jsfiddle.net/reblace/bWp8L/2/
A key takeaway is that you can update the data (including adding additional series) and the whole thing will redraw correctly according to the new nested join.
I often have charts that require a design element like a curly brace to call attention to call attention to a range or comparison in a graph, such as the y-difference in two points at the end of a graph.
My first take is that this would be a job for Highcharts Renderer API. Load the graph, and run a callback that adds an image (or line, shape, whatever) via chart.renderer.image(...) or similar.
That's the approach I have started down, but I'm just missing how to get the coordinates for chart data points within the callback. Here's a working codepen of the code below. What doesn't work is that there's no logic to give it proper placement on the canvas (suppose I want the bracket to go from the final top point to the final bottom point)
$('#container').highcharts({
data: { table: document.getElementById('datatable') },
chart: { type: 'line' },
title: { text: 'Data extracted from a HTML table in the page'
}
}, function(chart){
var img = 'http://upload.wikimedia.org/wikipedia/commons/thumb/4/4b/Curly_bracket_right.svg/30px-Curly_bracket_right.svg.png';
// How can I populate these values?
var x = 0; // should programmatically get x-position of last point
var y = 0; // should programmatically get y-position of last point
var h = 100; // should programmatically get distance between y-position of top and bottom points
var w = 50;
chart.renderer.image( img, x, y, w, h ).add();
});
Is there a straightforward way to populate those values? Or is there a better way to do this entirely?
to get the position you want you can use few methods provided by highcharts in their API.
methods like toPixels(), toValue() will help you to alter your required position as per the chart demogrphics.
please refer their api
toPixels() : http://api.highcharts.com/highcharts#Axis.toPixels()
toValue() : http://api.highcharts.com/highcharts#Axis.toValue()
hope using this will solve your requirement of positioning