Adding custom non-uniform labels to a Y-axis of a stacked area chart in NVD3 - nvd3.js

I want a stacked area chart of several datasets. possibly unusually I want to use the y axis to clarify what each set represents and its starting value.
i.e. The Y-axis doesn't need to be a regular tick over the range of the data.
for the sets:
[
{key: 'the first set', values: [x: 0, y: 4]},
{key: 'the second set', values: [x: 0, y: 10]},
]
the y-axis should have a tick at 4 labelled: 'the first set: 4', and another at 10 labelled: 'the second set: 10'
nv.addGraph(function() {
var chart = nv.models.stackedAreaChart()
.showLegend(false)
.showControls(false);
var data = [
{
key: 'first',
values: [
{ x: 0, y: 2 },
{ x: 2, y: 4 },
{ x: 4, y: 6 },
{ x: 6, y: 8 }
]
},
{
key: 'second',
values: [
{ x: 0, y: 4 },
{ x: 2, y: 6 },
{ x: 4, y: 8 },
{ x: 6, y: 10 }
]
}
];
var firstItemsLabels = ['', 'first', 'second', ''];
var firstItemsValues = [0, 2, 4, 10];
//the below doesn't seem to make any difference
//var firstItemsLabels = ['first', 'second'];
//var firstItemsValues = [2, 4];
chart.yAxis.tickValues(firstItemsLabels);
chart.yAxis.tickFormat(function(d, i) {
console.log('getting tick format for d: "' + d + '" at i ' + i);
console.log('for i: ' + i + ' = ' + firstItemsValues[i]);
var result = firstItemsValues[i];
return result;
});
d3.select('#chart svg')
.datum(data)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.css" rel="stylesheet">
<div id="chart">
<svg></svg>
</div>
I thought that the code in this snippet should achieve that but it doesn't
The console log output from that snippet...
getting tick format for d: "" at i 0
for i: 0 = 0
getting tick format for d: "first" at i 1
for i: 1 = 2
Error: Invalid value for <g> attribute transform="translate(0,NaN)
getting tick format for d: "0" at i undefined
for i: undefined = undefined
getting tick format for d: "18" at i undefined
for i: undefined = undefined
...confuses me because tickformat is looking for a value of 18 at one point which isn't in the dataset.
Am I trying to achieve something impossible? If not, since I'm clearly doing it wrong, how can it be done?

If I understand your goal correctly, you can use:
chart.yAxis.tickValues([4,10]);
chart.yAxis.tickFormat(function(d, i) {
if (d === 4 || d == 10) {
return "the first set: " + d
}
});
See this Plunk for a working example:
http://plnkr.co/edit/sdM14ebvv8cYCvOtX8em?p=preview

Related

How can I determine if a point is hidden on a 3D Scatterplot (Plotly.js)?

I'm using Plotly.js to draw a 3-D scatter plot . On zoom , I want to check which points are visible . Can this be done on svg level ? or any plotly expert ?
Snippet:
var myPlot = document.getElementById("myDiv");
var trace = {
x: [1, 7, 2, 4,1],
y: [12, 9, 15, 12,2],
z: [1, 2, 4, 8,4],
// x: [1,2],
//y: [12,15],
//z: [1, 4],
mode: 'markers' ,
type: 'scatter3d' ,
marker: {size:5 }
}
var data = [trace];
var layout = {
margin: {
l: 0,
r: 0,
b: 0,
t: 0} ,
//title: {text: 'ReOptim8 Scatter Plot'},
scene: {
yaxis:{title: 'X-axis'},
xaxis:{title: 'y-axis'},
zaxis:{title: 'z-axis'},
camera: {eye: {x:1.25, y:1.25, z:1.25}}
}
};
var config = {
displayModebar : true,
displaylogo: false,
responsive: true
};
Plotly.plot( myPlot, data, layout, config );
Code pen link below :
https://codepen.io/aniwar/pen/wLOzZv

C3.js combination chart with time series - tooltip not functional

I've been trying for 3 days to get this chart to display the way I want it to. Everything was working 100% until I realized the grouped bar chart numbers were off.
Example: When the bottom bar value equals 10 and the top bar value equals 20, the top of the grouped bar read 30. This is the default behavior, but not how I want to represent my data. I want the top of the grouped bar to read whatever the highest number is, which lead me to this fiddle representing the data exactly how I wanted to.
After refactoring my logic, this is what I have so far. As you can see the timeseries line is broken up and the tooltip is not rendering the group of data being hovered over.
My questions:
1) How to get the tooltip to render all three data points (qty, price, searches)
2) How to solidify the timeseries line so it's not disconnected
Any help would be greatly appreciated so I can move on from this 3 day headache!
Below is most of my code - excluding the JSON array for brevity, which is obtainable at my jsfiddle link above. Thank you in advance for your time.
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x-axis',
type: 'bar',
json: json,
xFormat: '%Y-%m-%d',
keys: {
x: 'x-axis',
y: 'searches',
value: ['qty', 'searches', 'price']
},
types: {
searches: 'line'
},
groups: [
['qty', 'price']
],
axes: {
qty: 'y',
searches: 'y2'
},
names: {
qty: 'Quantity',
searches: 'Searches',
price: 'Price ($)'
},
colors: {
price: 'rgb(153, 153, 153)',
qty: 'rgb(217, 217, 217)',
searches: 'rgb(255, 127, 14)'
}
},
bar: {
width: {
ratio: 0.60
}
},
axis: {
x: {
type: 'timeseries',
label: { text: 'Timeline', position: 'outer-right' },
tick: {
format: '%Y-%m-%d'
}
},
y: {
type: 'bar',
label: {
text: 'Quantity / Price',
position: 'outer-middle'
}
},
y2: {
show: true,
label: {
text: 'Searches',
position: 'outer-middle'
}
}
},
tooltip: {
grouped: true,
contents: function(d, defaultTitleFormat, defaultValueFormat, color) {
var data = this.api.data.shown().map(function(series) {
var matchArr = series.values.filter(function(datum) {
return datum.value != undefined && datum.x === d[0].x;
});
if (matchArr.length > 0) {
matchArr[0].name = series.id;
return matchArr[0];
}
});
return this.getTooltipContent(data, defaultTitleFormat, defaultValueFormat, color);
}
}
});
1) If I got it right, you want tooltip to show all values, even if some of them are null.
Null values are hidden by default. You can replace them with zero (if it is suitable for your task) and thus make them visible.
Also, it seems to me that there is a shorter way to get grouped values:
var data = chart.internal.api.data().map(function(item) {
var row = item.values[d[0].index]; // get data for selected index
if (row.value === null) row.value = 0; // make null visible
return row;
});
2) I think you are talking about line.connectNull option:
line: {
connectNull: true
}
UPDATE
Looks like having duplicate keys breaks work of api.data() method.
You need to change json structure to make keys unique:
Before:
var json = [
{"x-axis":"2017-07-17","qty":100},
{"x-axis":"2017-07-17","price":111},
{"x-axis":"2017-07-17","searches":1},
{"x-axis":"2017-07-18","qty":200},
{"x-axis":"2017-07-18","price":222},
{"x-axis":"2017-07-18","searches":2}
];
After:
var json = [
{"x-axis":"2017-07-17","qty":100,"price":111,"searches":1},
{"x-axis":"2017-07-18","qty":200,"price":222,"searches":2}
];
See fiddle.

Highcharts - draw line chart with summed values but show breakup on hover

I am using Highcharts - Line - Ajax.
Let's say I have two series of data - 'Headcount 1' and 'Headcount 2'. I want to draw a line graph of 'Headcount', which is the sum of the 2 series. However, when someone hovers on one data point, I want to show the individual values in the callout. Is this possible? How can I do this?
e.g.
H1 = (1, 2, 3)
H2 = (5, 6, 7)
Ht = (6, 8, 10)
I will draw a line graph with Ht. If I hover on '6' on the chart, the callout should show the values of H1 = 1 and H2 = 5
You can set the visibility for series H1 and H2 to false,
series: [{
name: 'H1',
data: [1, 2, 3],
visible: false,
showInLegend: false
}, {
name: 'H2',
data: [5, 6, 7],
visible: false,
showInLegend: false
}, {
name: 'H',
data: [6, 8, 10]
}]
and edit tooltip formatter to display what you want
tooltip: {
formatter: function() {
var s = '<b>' + this.x + '</b>';
var chart = this.points[0].series.chart; //get the chart object
var categories = chart.xAxis[0].categories; //get the categories array
var index = 0;
while(this.x !== categories[index]){index++;} //compute the index of corr y value in each data arrays
$.each(chart.series, function(i, series) { //loop through series array
if (series.name !== 'H') {
s += '<br/>'+ series.name +': ' +
series.data[index].y +'m'; //use index to get the y value
}
});
return s;
},
shared: true
}
Have a look at jsfiddle.net/s190ebby/27/
Yes
Points can have custom property, taking care that the names do not shadow highcharts variable names.
var data = [{
y: 6,
h1Value: 1,
h2Value: 5
},{
y: 8,
h1Value: 2,
h2Value: 6
}];
Set your series to this data in your config object, by series: data
Customise the tooltip as:
tooltip: {
pointFormat: '<b>H Value</b>: {point.y}<br/>
<b>H1 Value</b>: {point.h1Value}<br/>
<b>H2 Value</b>: {point.h2Value}'
}

ZoomRange Highstock works not correct?

I made a Highstock diagramm and got aproblem with zooming on the yAxis.
I have a Button and 2 textfield to get the wanted min/max values for the axis. With min:0, max: 100 it works well. With min:0, max:80 it doesn't (max will still be 100 in the Diagramm).
If I use the mouse for zooming it works well (even a min of: 3.7 and a max of 3.894 is possible). But using the mouse is not an Option, because in the later Diagramm there will be 3 yAxes with individual zoom.
$(function () {
var seriesOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'];
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
function createChart() {
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
chart:{
zoomType: 'xy'
},
yAxis: [
{
labels: {
format: '{value}',
},
height: '100%',
opposite: false,
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
],
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
},
function(chart){
$('#btn').click(function(){
var min = temp_min.value,
max = temp_max.value;
chart.yAxis[0].setExtremes((min),(max));
});
});
}
$.each(names, function (i, name) {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
if(seriesCounter==0){
seriesOptions[i] = {
name: name,
data: data,
yAxis: 0
};
} else {
seriesOptions[i] = {
name: name,
data: data,
yAxis: 0
};
}
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});
});
JSFiddle
Another Question: Is it possible to set up a scrollbar for the yAxis as well?
Thanks for your help, Patrick
This is related with fact that tickInterval is not regular, so is rounded to value (like 100). The solution is using tickPositioner which calculates ticks, based on extremes which you define.
tickPositioner: function (min,max) {
var positions = [],
tick = Math.floor(min),
increment = Math.ceil((max - min) / 5);
for (tick; tick - increment <= max; tick += increment) {
positions.push(tick);
}
return positions;
},
http://jsfiddle.net/6s11kcwd/
The scrollbar is supported only for xAxis.

jqplot tooltipContentEditor displays wrong x and y values

I have a jqplot line graph with this line:
`var line = [[1,0.493],
[1,1.286],
[2,0.305],
[2,0.516],
[2,0.551],
[2,0.595],
[2,0.609],
[2,0.644],
[2,0.65],
[2,1.249],
[2,1.265],
[4,0.443],
[5,0.288],
[5,0.477],
[5,0.559],
[5,0.562],
[6,0.543],
[7,0.513],
[7,0.549],
[8,0.442],
[8,0.467],
[8,0.468],
[8,0.597],
[8,0.857]];`
Im using tooltipContentEditor to display the x and y values of the point on hover. I need the values displayed to be exact.
Here is the code Im using: http://jsfiddle.net/ZQh38/1/
The problem:
Sometimes, the x and y values displayed are incorrect. For example, the last points at (6, 0.5) and (7, 0.5)
The values are only displayed with 1 decimal, which needs to be 3.
So, the question is, how do I get the exact y values?
Ive also tried to use the pointIndex, which does NOT match with the values in the line.
Thanks for your help!
Here is the solution to your problem: jsFiddle example
I made changes to your highlighter option.
/*
Drawing graphs
*/
var Statistics = {
scatter: false,
trendline: false,
enableLabels: true,
showAverage: false,
colour: null,
//Graph properties
scatterPlot: function(on){
Statistics.scatter = on;
},
showTrendline: function(on){
$.jqplot.config.enablePlugins = on;
Statistics.trendline = on;
},
disableLabels: function(yes){
Statistics.enableLabels = (!yes);
},
shouldDrawScatter: function(){
return (!Statistics.scatter);
},
useLabels: function(){
return Statistics.enableLabels;
},
getTrendline: function(){
return Statistics.trendline;
},
//Drawing
drawLabels: function(){
document.getElementById('ylabel').innerHTML = Statistics.ylabel;
document.getElementById('xlabel').innerHTML = Statistics.xlabel;
},
generateGraph: function(){
var line = [[1,0.493],
[1,1.286],
[2,0.305],
[2,0.516],
[2,0.551],
[2,0.595],
[2,0.609],
[2,0.644],
[2,0.65],
[2,1.249],
[2,1.265],
[4,0.443],
[5,0.288],
[5,0.477],
[5,0.559],
[5,0.562],
[6,0.543],
[7,0.513],
[7,0.549],
[8,0.442],
[8,0.467],
[8,0.468],
[8,0.597],
[8,0.857]];
var plot = $.jqplot('chart', [line], {
animate: true,
grid:{backgroundColor: 'white'},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: [1, 2, 3, 4, 5, 6, 7],
tickOptions: {
fontFamily: '"Helvetica", cursive',
fontSize: '12pt'
}
},
yaxis: {
tickOptions: {
fontFamily: '"Helvetica", cursive',
fontSize: '12pt'
},
max: 2,
min: 0
}
},
series:[{
color: "#594A42",
lineWidth: 2.5,
shadow: false,
fillColor: "#594A42",
markerOptions: {
style:'filledCircle',
color: "#594A42",
shadow: false,
size: 10
},
showLine: false,
trendline: {
color: '#999'
},
rendererOptions:{
animation: {
speed: 2000 //Speeding up animation
}
}
}],
highlighter: {
show: true,
fadeTooltip: true,
sizeAdjust: 6,
tooltipContentEditor: function(str, pointIndex, index, plot){
var splitted = plot._plotData[1][index];
var x = splitted[0];
var y = splitted[1];
return x + ", " + y;
}
}
});
},
//Checks if the graph will be a straight line
straightLine: function(lineArray){
if(typeof lineArray != 'undefined' && lineArray.length > 0) {
for(var i = 1; i < lineArray.length; i++)
{
if(lineArray[i] !== lineArray[0])
return false;
}
}
return true;
},
};
Statistics.generateGraph();

Resources