js chart non uniform x values - javascript

Is there a JS Charting lib that supports multiple curces, having unequal steps?
Consider data like that:
Curve 1 (x/y pairs) RED in Sample:
[1, 10] [10, 20] [20,20]
Curve 2 Green in Sample:
[1, 2] [5, 6] [10,10] [11,12] [15,15] [20,20]
This should result in 2 Curves with x RANGE from 1..20. The first only has 3 data points that should be connected by a line. The second has 6 Points in the same x value range.
Which JS Charting library can handle that?

most likely, any chart lib can handle,
just need to load the data in the format the chart accepts
here, google charts is used to draw the chart
google charts has a method to join tables
so, just create two data tables, one for each x range
the resulting joined table will fill in the missing values with null
as such, need option for interpolateNulls so there are no breaks in the lines
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var x0 = [
[1, 10], [10, 20], [20,20]
];
var x1 = [
[1, 2], [5, 6], [10,10], [11,12], [15,15], [20,20]
];
var data0 = google.visualization.arrayToDataTable(x0, true);
var data1 = google.visualization.arrayToDataTable(x1, true);
var joinData = google.visualization.data.join(
data0, data1, 'full', [[0, 0]], [1], [1]
);
var options = {
height: 400,
interpolateNulls: true,
legend: {
position: 'none'
},
vAxis: {
viewWindow: {
max: 30
}
},
hAxis: {
viewWindow: {
max: 30
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(joinData, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

plotly colorscale in scatter data plot

Using marker:{color:x} in javascript plotly (http://jsfiddle.net/d8bt1qof/), I can color-code my
data:
But how can I change the colorscale?
Different colorscales seems to be available (https://plotly.com/javascript/colorscales/), but the usage is only explained for heatmap plots. And adding colorscale: 'Portland' seems not to work.
scattergl trace markers can also have a colorschale. I found a reference for it in the documentation here:
colorscale
Parent: data[type=scattergl].marker
Type: colorscale
Sets the colorscale. Has an effect only if in marker.coloris set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, [[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]. To control the bounds of the colorscale in color space, usemarker.cmin and marker.cmax. Alternatively, colorscale may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,Earth,Electric,Viridis,Cividis.
So an example based on your fiddle you could look like this:
var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var trace1 = {
x: x,
y: x,
mode: 'markers',
marker: {
size: 20,
color: x,
colorscale: 'Greens'
},
};
Plotly.newPlot('myDiv', [trace1], {});
Here is an implementation for a custom colorscale based on the viridis colour scale R users will be familiar with.
var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var y = vector_normalise(x);
var trace1 = {
x: x,
y: x,
mode: 'markers',
marker: {
colorscale: [
[0.000, "rgb(68, 1, 84)"],
[0.111, "rgb(72, 40, 120)"],
[0.222, "rgb(62, 74, 137)"],
[0.333, "rgb(49, 104, 142)"],
[0.444, "rgb(38, 130, 142)"],
[0.556, "rgb(31, 158, 137)"],
[0.667, "rgb(53, 183, 121)"],
[0.778, "rgb(109, 205, 89)"],
[0.889, "rgb(180, 222, 44)"],
[1.000, "rgb(253, 231, 37)"]
],
color: y,
size: 20,
},
};
Plotly.newPlot('myDiv', [trace1], {});
Below is my normalisation function, I have left it verbose to help with understanding. The input vec could be overwritten and returned to reduce local variables if desired.
function vector_normalise(vec) {
var vmin = Math.min(...vec);
var vmax = Math.max(...vec);
// calculate the delta to save time with big arrays
var vdelta = vmax - vmin;
// create an empty array to return
var vec_ret = [];
// push doesn't seem to like inline functions
var vnorm;
// iterate over the array/vector
vec.forEach(value => {
vnorm = (value - vmin) / vdelta;
vec_ret.push(vnorm);
})
return vec_ret
}
Edit: Turns out Viridis is one of the existing available palettes... 😉

append multiple y axis data in plotly JS

I want to draw a multiline chart with a dataSet(multiple lists append in 1 list) where I know which one I will as X-axis and Y-axis.
let dataSet = [[1, 2, 3, 4], [10, 15, 13, 17], [16, 5, 11, 9]];
/**
X-axis = dataSet[0]
The remaining will be used as Y-axis*/
The example is taken from here. Where I have seen for plotting each line(here 2 times) variable is calling to set the data. In my case, Y-axis will appear near about 30 times and for each X-axis value will be the same. But I haven't found a dynamic solution where I can append the Y-axis value using a for loop or something like that. That means I want to call this data variable only 1 time and want to append all information of multi-chart there at instant.
I have added my approach here.
let dataSet = [[1, 2, 3, 4], [10, 15, 13, 17], [16, 5, 11, 9]];
function get_val (data){
let x = [];
for(let j = 1;j<data.length;j++)
{
x.push(data[j]);
}
//console.log("x: ",x);
return x;
}
var trace1 = {
x: dataSet[0],
y: get_val(dataSet), /* if write here get_val(dataSet)[0] then works fine*/
type: 'scatter'
};
/**
if you uncomment the following lines, result will be as like as the example of plotly JS
*/
/*
var trace2 = {
x: dataSet[0],
y: get_val(dataSet)[1],
type: 'scatter'
};
*/
var data = [trace1/*, trace2*/];
Plotly.newPlot('myDiv', data);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
So, I want to know is there any approach by following which I can add multiple time any axis within a single variable(here trace1).
I have understood(maybe) where was my lacking.
1/ At first I have realized that I have overlooked that the traces or datapoints of plotly is an array of objects.
2/ I have also tried to organize my data
I have given here the solution that I have done.
let dataSet = [[10, 20, 30, 40], [10, 15, -13, 17], [1-6, 5, 11, 20] ]
/** following function will take the data and return the dataTRace as per as plotly's requirements.*/
function make_trace({data, set_type = "scatter", set_mode = "lines"} = {}){
let dataPoint = [];
for(let i = 1; i<data.length; i++){
dataPoint.push({
x: data[0],
y: data[i],
mode: set_mode,
type: set_type,
name: 'y_' + i
});
}
return dataPoint;
}
/** following function will make the layout for the plot*/
function make_layout({given_title="the title is not provided",x_min=0,x_max=15,x_axis_title="x_axis", y_min=0,y_max=15, y_axis_title="y_axis"} = {})
{
let layout_object = {
title: {
text: given_title
},
showlegend: true,
xaxis: {
range: [x_min, x_max],
title: x_axis_title
},
yaxis: {
range: [y_min, y_max],
title: y_axis_title
},
};
return layout_object;
}
let fig_layout = make_layout({given_title:"x vs y1, y2 plot",
x_min: 10, x_max : 50, x_axis_title:"x",
y_min: -20, y_max: 20, y_axis_title : "y(1,2)"});
Plotly.newPlot('myDiv', make_trace({data : dataSet, set_type:"scatter", set_mode : "lines"}), fig_layout);
Plotly.newPlot('myDiv_1', make_trace({data : dataSet, set_type:"scatter", set_mode : "markers"}), fig_layout);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
<div id='myDiv_1'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>

Google Charts - Format vAxis point instead of comma

How to format vAxis in google charts that would display vertical scale with points instead of commas.
Example(now): 100,000
Example(then): 100.000
I know that the trick is with 'format' function, but I can't get it to work like i want.
I am trying to format it like with this:
vAxis: {minValue:0, format:'##.##'}
if the format option does not meet your needs,
you can use the ticks option to provide custom labels
using object notation, you can provide both the...
v: - value for the axis
f: - formatted value for the label
{v: 100000, f: '100.000'}
see following working snippet
the NumberFormat class is used, in an attempt to create the format
(not sure exactly what is needed)
data table method getColumnRange is used to find the range of the y-axis
a loop builds each tick for the axis labels...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'y0');
data.addRows([
[0, 500000],
[1, 500000],
[2, 200000],
[3, 700000],
[4, 400000]
]);
var formatNumber = new google.visualization.NumberFormat({
groupingSymbol: '.',
fractionDigits: 0
});
var ticksY = [];
var yRange = data.getColumnRange(1);
for (var i = 0; i <= yRange.max; i=i+100000) {
ticksY.push({
v: i,
f: formatNumber.formatValue(i)
});
}
var options = {
vAxis: {
ticks: ticksY
}
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div')
);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Try this :
vAxis.format:{format:'##.##'}

How to add percentage label without changing order by Google Chat

I want to add percentage marks to number labels and found a option for it.
{hAxis: {format: 'percent'}}
But it also multiple the number by 100.
For instance, {hAxis: { format:'#,###%'} } displays the values "1,000%", "750%", and "50%" for values 10, 7.5, and 0.5.
https://developers.google.com/chart/interactive/docs/customizing_axes#number-formats
How can I just add % to the labels?
you could try adding custom axis labels, or ticks...
using object notation, you can provide both a...
value (v:) and a formatted value (f:)
then using google's NumberFormat class, build each tick manually...
var formatPercent = new google.visualization.NumberFormat({
suffix: '%'
});
...
ticks.push({
v: data.getValue(i, 0),
f: formatPercent.formatValue(data.getValue(i, 0))
});
...
hAxis: {
ticks: ticks
}
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['X', 'Y'],
[1, 1],
[10, 2],
[20, 3],
[30, 4]
]);
var formatPercent = new google.visualization.NumberFormat({
pattern: '#,##0',
suffix: '%'
});
var ticks = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
ticks.push({
v: data.getValue(i, 0),
f: formatPercent.formatValue(data.getValue(i, 0))
});
}
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {
hAxis: {
ticks: ticks
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Charts Get maximum scale

I'm trying to make an all positive bubble chart have quadrants by drawing the quadrants using the baseline property like so:
var dataT = google.visualization.arrayToDataTable(.....);
var options = {
hAxis: {title: 'h axis',baseline:100},
vAxis: {title: 'v axis',baseline:20},
...}
var chart = new google.visualization.BubbleChart(...);
chart.draw(dataT,options);
Except the graph will keep changing depending on the query so the baselines will not be the same for all the graphs. I would like to be able to get the max axis value and divide it by 2 to set the baselines right in the middle of each axis.
Example:
var options = {
hAxis: {title: 'h axis',baseline:max_h_axis/2},
vAxis: {title: 'v axis',baseline:max_v_axis/2},
...
Is there any way of knowing the max axis values of the graph before drawing the graph?
the getColumnRange method works for this...
Returns the minimal and maximal values of values in a specified column. The returned object has properties min and max. If the range has no values, min and max will contain null.
you can also use this information to produce your own axis tick marks.
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['X', 'Y'],
[8, 120],
[4, 155],
[11, 140],
[4, 205],
[3, 35],
[6, 78]
]);
var ticksX = [];
var ticksY = [];
var numberOfTicks = 10;
var rangeX = data.getColumnRange(0);
var rangeY = data.getColumnRange(1);
var stepX = Math.ceil((rangeX.max - rangeX.min) / numberOfTicks);
for (var i = rangeX.min - stepX; i <= rangeX.max + stepX; i = i + stepX) {
ticksX.push(i);
}
var stepY = Math.ceil((rangeY.max - rangeY.min) / numberOfTicks);
for (var i = rangeY.min - stepY; i <= rangeY.max + stepY; i = i + stepY) {
ticksY.push(i);
}
var baseX = Math.ceil((rangeX.max - rangeX.min) / 2) + rangeX.min;
var baseY = Math.ceil((rangeY.max - rangeY.min) / 2) + rangeY.min;
var options = {
hAxis: {
title: 'h axis',
baseline: baseX,
ticks: ticksX
},
vAxis: {
title: 'v axis',
baseline: baseY,
ticks: ticksY
},
legend: 'none',
height: 600,
width: 600
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Categories