weird series sorting problem in Highcharts bar chart - javascript

Full code example here: https://jsfiddle.net/_dario/o6nugkrw/24/
I have a data series structured like this (from an API call):
{
"mango": 12736,
"orange": 8906,
"banana": 8404,
"2020": 8239,
"blackberry": 7703,
"pear": 7297,
"raspberry": 6895,
"apple": 6432,
"kiwi": 6202,
"tomato": 6189,
"1995": 6123,
"kumquat": 6038,
"melon": 5982,
"strawberry": 5973,
"pineapple": 5441
}
The sorting order is value high to low, regardless of the label. These are to be plotted in an Highcharts horizontal bar chart.
Notice there are two numeric (string, though) labels: "1995" and "2020".
This specific data format is then parsed for Highcharts:
//--previous highcharts options
series: Object.keys(data).map((s, index) => {
let arr = new Array(length).fill(null, 0, length);
arr[index] = data[s];
return {
name: s,
data: arr,
tooltip: {
headerFormat: ''
},
}
}),
//--subsequent highcharts options
as per the jsfiddle example (https://jsfiddle.net/_dario/o6nugkrw/24/), the sorting order along the Y axis in the chart is different, and no matter what the order the data is presented in, the two "numeric" labels always stay on top and are sorted differently (by numeric value).
I found no reference in the Highcharts docs about this and would like to have them treated as "words" like the others and sorted accordingly. I believe the error might be in the parsing above, but cannot find it.

Related

apexcharts different options for axis range

Let's take a look at the simple chart data:
it has (x,y) pairs:
x
y
0
-3
1
2
2
7
3
8
4
15
5
0
The idea is to create a basic line chart, using VueJS in my case, but the idea can be generalized to JavaScript.
I have a series array of objects, where each object has x and y coordinates:
series = [
{
x: 0,
y: -3
},
{
x: 1,
y: 2
},
...
]
This series is part of options object:
const options = {
chart: {
type: 'line'
},
series: series
}
const chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
And the chart is rendered.
Now, let's say I want to append the data to that chart - add 2 new (x,y) pairs
const newData = [
{
x: 6,
y: 20
},
{
x: 7,
y: -10
}
]
chart.appendData([{ data: chartData }])
I would also like that newly appendedData has, for example, different color, fill, or something else - so newly added data displays differently than old data.
Feel free to point me to documentation if I missed anything, but I searched through apex chart methods, and the only thing that looks remotely close to this would be inside
updateOptions() method, the redrawPath flag (updateOptions docs:
When the chart is re-rendered, should it draw from the existing paths
or completely redraw the chart paths from the beginning. By default,
the chart is re-rendered from the existing paths
In order to style the new data differently, you'll want to put these data points into a different series using the appendSeries method:
const newData = [
{
x: 6,
y: 20
},
{
x: 7,
y: -10
}
]
chart.appendSeries({
name: "series-2", // optional
data: newData
})
Most of the styling in ApexCharts is done based on series (more specifically seriesIndex). So by placing the new data in a separate series you'll be able to style this second series using an array of, for example, colors.
You could either specify the color you would like to use as you append the new series of data using the updateOptions method you mention, or you can specify it in advance.
chartOptions: {
colors: ["#546E7A", "#E91E63"],
}
When working with "Numeric paired values in XY properties", the xaxis type also has to be explicitly set to numeric:
chartOptions: {
xaxis: {
type: 'numeric',
},
}
The tricky bit comes when you want to add more data a second time (or third, more time). There are two approaches I can think of here:
Shuffle the existing data across to the original series (append series-2 to series-1) - and overwrite series-2 with your new data. You don't need to edit the colors in chartOptions.
You could shuffle the colors along. If you want all "old" data to have the same color, simply prepend the colors array with your base color every time you add a new series. Or if you want each series to have a different color, just append a color every time you add a new series.

Highcharts with custom scaling in upper regions

I would like to know how to achieve a custom scale for a chart in Highcharts. I want to display a boxplot which has very high whiskers. The normal values to display are between 500 and 1000 but there are some anomalies which are about 6000 on y-axis. This is causing the whole chart to be squeezed and the scaling is so small that you can't determine the boxplots correctly. I would like to increase the tick-size between 1000 and 6000 to decrease the heigt of the chart.
Highcharts provides breaks functionality that seems to be ideal for your case: https://api.highcharts.com/highcharts/yAxis.breaks
Another approach is to change the yAxis type to logarithmic: https://api.highcharts.com/highcharts/yAxis.type
EDIT
The discussion in the comments section reveals that the OP needs rather custom y axis formatting than breaks functionality.
Here's how to approach this issue:
The problem here is that axes in Highcharts can only have either constant or logarythmic scales. Your example shows irregular scale - the values are not in constant or logarythmic order ([0, 3, 10, 30, 150]).
Here's what I've done to mimic that kind of look and behaviour:
I set tickPositions to [0, 1, 2, 3, 4] - these are the actual values that appear on the chart. As you can see the distance between all these numbers is constant: 1.
Then I used formatter to display corresponding number from ranges array for each label.
yAxis: {
tickPositions: [0, 1, 2, 3, 4],
labels: {
formatter: function() {
return ranges[this.pos];
}
}
},
Before I passed the data to the chart constructor I converted all the values so that they're between 0 and 4:
series: [{
data: [2, 120].map(function(val) {
var range = findRange(val);
var y = range.index + (val - range.low) / (range.high - range.low);
return {
y: y,
originalValue: val
};
})
}]
Finally I used originalValue property in tooltip.format string to print to the user the number before the conversion.
tooltip: {
pointFormat: "<span style='color:{point.color}'>\u25CF</span> {series.name}: <b>{point.originalValue}</b><br/>"
},
This example is simplified to the line series case but can be easily adjusted to boxplot series. The code serves only for the example purposes and should be improved - it's easy to cause an error within it.
Live working demo: https://jsfiddle.net/kkulig/ytjz1jej/
API references:
https://api.highcharts.com/highcharts/tooltip.pointFormat
https://api.highcharts.com/highcharts/yAxis.tickPositions
https://api.highcharts.com/highcharts/xAxis.labels.formatter

How can I create a horizontal stacked bar chart with labels on the bars themselves as well as labels above the bars?

I'm trying to create a horizontal stacked bar chart with labels on the bars themselves (currently using dataLabels) as well as labels just above the bars.
Here is a JSFiddle I've created that somewhat resembles what I am trying to accomplish. In this example I've placed the labels using plotLine labels, but I'm having a difficult time figuring out how to place the bars correctly in my real use case as I get the data for the bars through Ajax calls.
JSFiddle
I've experimented with stackLabels, plotLine labels as well as plotBand labels but to no avail. How can I place labels above the bars correctly every time?
I would use plotBands instead of plotLines - you can better control the alignment within the band, which can be set to cover the same portion of the graph as the bar itself.
An example.
Using your series data:
var series = [{
name: 'John',
data: [5]
},
{
name: 'Jane',
data: [2]
}, {
name: 'Joe',
data: [3]
}]
We can loop through and build a plotBands array from the same data:
var bands = [],
prevData = 0;
$.each(series, function(i,ser) {
var point = ser.data[0],
name = ser.name;
bands.push({
from: prevData,
to: (prevData + point),
color: 'rgba(255,255,255,0)',
label: {
text: name,
align: 'center'
}
});
prevData = (prevData+point);
});
To make this match the order of the series as plotted, we need to set reversedStacks: false on the yAxis, as by default, Highcharts reverses the order of the series. Then we populate the plotBands with our generated array:
yAxis: {
reversedStacks: false,
plotBands: bands
}
In this way you can make use of the full feature set of the plotBands label properties.
Updated fiddle:
http://jsfiddle.net/jlbriggs/xwzfjbhe/4/
And this adjusts to fit however many data points you have, provided you keep the same format (series.name, series.data[0]):
http://jsfiddle.net/jlbriggs/xwzfjbhe/5/
There are a number of other ways you can go about this as well, including:
The labels property: http://api.highcharts.com/highcharts/labels
The renderer function: http://api.highcharts.com/highcharts/Renderer

How to duplicate Y Axis on JQuery Flot

I'm being able to use JQuery Flot, and it's a very nice tool. However, I could not find a GOOD solution for my problem.
I want to duplicate Y axis, so I can display 1 on the left and 1 on the right, so the users, when comparing data from the rightmost side of the chart, won't have to scroll through the leftmost side of the chart. I'm assuming they will be accessing it through a smartphone.
JQuery Flot allows multiple axis, but for each axis, I would need a different set of data, as in this example:
http://people.iola.dk/olau/flot/examples/multiple-axes.html
But I don't want to duplicate the data. Can't I just 'tell' Flot to duplicate the yaxis using the same set of data?
You can use the hooks functionality to force flot to show the second yaxis even though it has no data series assigned to it:
// hook function to mark axis as "used"
// and assign min/max from left axis
pOff = function(plot, offset){
plot.getYAxes()[1].used = true;
plot.getYAxes()[1].datamin = plot.getYAxes()[0].datamin;
plot.getYAxes()[1].datamax = plot.getYAxes()[0].datamax;
}
$.plot("#placeholder2", [ { data: d2 } ], {
hooks: { processOffset: [pOff] },
yaxes: [ {},
{position: 'right'} // add second axis
]
});
Depending on how your axis is configured though, this might be messy. You'll have to steal parameters from the left axis to get it to work (as I've done above with datamin/datamax).
If it was my code, I'd go with your duplicate data approach. You aren't really duplicating anything, just assigned the same array to two series. I'd then configure the 2nd series to simply not draw.
var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];
// use the same data but toggle off the lines...
$.plot("#placeholder", [ { data: d2 }, {data: d2, yaxis: 2, lines: {show: false}} ], {
yaxes: [ {},
{position: 'right'} ]
});
Here's a fiddle demonstrating the two approaches.

Highcharts: passing additional information to a tooltip

I have an array of data points that I am passing to a Highcharts chart that looks like
mydata = [{
x: 1,
y: 3,
nameList: ["name1", "name2"]
}, {
x: 2,
y: 4,
nameList: ["name3", "name4"]
}]
I build the chart like this:
$("#chart").highcharts("StockChart", {
series: [{
data: mydata
}, {
data: yourdata
}]
});
Now, I would like to be able to access the nameList array from the shared tooltip, which I'm trying to do as follows:
tooltip: {
formatter: function() {
var s = "";
$.each(this.points, function(i, point) {
s += point.point.nameList;
});
return s;
},
shared: true
}
but when examining the point objects in Firebug using console.log(point), I can't seem to find the nameList entry anywhere in them. How could I access this auxiliary information in a shared series tooltip? All help is appreciated.
Eureka!
By default, Highcharts will accept several different types of input for the data of a series, including
An array of numerical values. In this case, the numberical values will be interpreted
and y values, and x values will be automatically calculated, either starting at 0 and
incrementing by 1, or from pointStart and pointInterval given in the plotOptions.
An array of arrays with two values. In this case, the first value is the x value and the
second is the y value. If the first value is a string, it is applied as the name of the
point, and the x value is incremented following the above rules.
An array of objects with named values. In this case the objects are point configuration
objects as seen below.
However, the treatment of type 3 is different from types 1 and 2: if the array is greater than the turboThreshold setting, then arrays of type 3 won't be rendered. Hence, to fix my problem, I just needed to raise the turboThreshold setting like so:
...
plotOptions: {
line: {
turboThreshold: longestArray.length + 1
}
},
...
and the chart renders the longestArray data properly. Hurray! The only drawback is that there is a considerable time spent rendering the data for much longer arrays due to "expensive data checking and indexing in long series." If any of you know how I might be able to bypass this checking or otherwise be able to speed up the processing of this data, I'd be extremely thankful if you'd let me know how.
I can see it here:
tooltip: {
formatter: function() {
var s = "";
console.log(this.points[0].point.nameList); // ["name1", "name2"]
$.each(this.points, function(i, point) {
s += point.point.nameList;
});
return s;
},
shared: true
}

Categories

Resources