Plotly line chart - multiple lines - javascript

I want to create a line chart with three lines (male,female,unknown). This is a sample of my data:
timestamp;sex;number
06:00;male;5
07:00;male;2
07:00;unkown;3
07:00;female;4
09:00;female;4
Is there a option in plotly to automatically create the three lines or do I need to loop through the data and create three traces by myself? This is my code so far:
var trace1 = {
type: 'scatter',
x: x,
y: y,
name: "Male",
transforms: [{
type: 'aggregate',
groups: x,
aggregations: [
{target: 'y', func: 'count', enabled: true},
]
}]
};
var data = [trace1];
Plotly.newPlot('myDiv', data, {title: 'Plotting CSV data from AJAX call'});

You need to create different data set(trace) for each category.
Maybe this can help you.
var men = {
x: x,
y: y,
type: 'scatter',
name:'male'
};
var female = {
x: x,
y: y,
type: 'scatter',
'name':'female'
};
var unknown = {
x: x,
y:y,
type: 'scatter',
'name':'unknown'
};
var data = [men, female,unknown];

Related

multiple line charts with independent data Javascript (Chart.js or google-vizualisation)

js and I have two datasets:
data1 = [[0,1],[2,3],[5,7]] and data2 = [[1,4],[2,6],[5,2],[7,1]] for example.
Each data list contains lists that represent points to plot on a same chart. (x and y values)
I want to plot exactely like this :
https://www.chartjs.org/samples/latest/charts/line/multi-axis.html
But as you can see, my data lists don't have the same x or y values and they don't even have the same size, so I can't use the regular:
data: {labels = [1,2,3,4,5],
data = [7,8,3,1,2],
data = [9,1,2,3,4]} //for example
How can I code this chart only with javascript (no jQuery please) ? I didn't find anything on the Internet that might help.
Any suggestions would matter to me !
You can use a scatter chart, that accepts the data as an array of objects containing x and y properties. To turn it into a line chart, define showLine: true inside the data configuration objects.
Given your data structures, the following line of code produces the data structure expected by Chart.js.
data1.map(o => ({ x: o[0], y: o[1] }))
Please have a look at below runnable code snippet.
const data1 = [[0,1],[2,3],[5,7]];
const data2 = [[1,4],[2,6],[5,2],[7,1]];
new Chart('line-chart', {
type: "scatter",
responsive: true,
data: {
datasets: [
{
data: data1.map(o => ({ x: o[0], y: o[1] })),
label: 'Dataset 1',
showLine: true,
fill: false,
borderColor: 'red'
},
{
data: data2.map(o => ({ x: o[0], y: o[1] })),
label: 'Dataset 2',
showLine: true,
fill: false,
borderColor: 'blue'
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="line-chart" height="80"></canvas>

Parse Datatime only show YYYY Plot.ly javascript

I've got a dataset which I am parsing into Plot.ly for use in javascript. The issue i have is that whereas my data is defined as 'yyyy-mm-dd hh:MM:ss' I only see yyyy after the parse. Wher eam i going wrong or what am i missing?
My script looks like this:
processData = function(dataset) {
// Data is in the dataset in a column based format, where each column
has an array of data
// eg. dataset.column_name[0].raw_data,
dataset.column_name[0].formatted_data
data={x: [], y1: [], y2: [], y3: [], y4: []}
for (i=0;i<dataset['datetime'].length;i++){
data['x'].push(parseFloat(dataset['datetime'][i].raw_data));
data['y1'].push(parseFloat(dataset['mp_price'][i].raw_data));
data['y2'].push(parseFloat(dataset['upper'][i].raw_data));
data['y3'].push(parseFloat(dataset['lower'][i].raw_data));
data['y4'].push(parseFloat(dataset['market_price'][i].raw_data));
}
return data
},
doDrawing = function(data, $chartDiv, height, width, errorFunction) {
// Use require to load the javascript libraries you need
// Libraries we ship with and their location:
// js/chartingLibraries/c3/c3
// js/chartingLibraries/chartjs/Chart
// js/chartingLibraries/d3_3.5.17/d3_3.5.17
require(['https://cdn.plot.ly/plotly-latest.min.js'], function(Plotly)
{
var trace1 = {
x: data['x'],
y: data['y1'],
mode: 'markers',
type: 'scatter',
name: 'Trade Price'
};
var trace2 = {
x: data['x'],
y: data['y2'],
mode: 'lines+markers',
type: 'line',
name: 'Upper Threshold'
};
var trace3 = {
x: data['x'],
y: data['y3'],
mode: 'lines+markers',
type: 'line',
name: 'Lower Threshold'
};
var trace4 = {
x: data['x'],
y: data['y4'],
mode: 'lines+markers',
type: 'line',
name: 'Market Price'
};
var layout = {
title: 'Off Market Trades',
xaxis: {
title: 'Year',
showgrid: true,
zeroline: false
},
yaxis: {
title: 'Trade Values and Thresholds',
showline: false
}
};
var data2 = [trace1, trace2, trace3, trace4];
Plotly.newPlot($chartDiv[0], data2, layout);
});
}
One row of data example would be:
datetime: 2018-11-22 09:28:15.0
mp_price: 5.2
market_price: 5.1
lower: 4.8
upper: 5.6

C3 creating a bar chart with categorical JSON data

How do you specify the x-axis labels for a C3 bar chart with data loaded via JSON? I don't see anything in the docs and the closest I found was this but it only gives an example for data specified in column format, whereas I have data specified in JSON format like in this example
My attempt:
const chart = c3.generate({
data: {
// x: "title",
json: bookData,
type: "bar",
keys: {
value: ["count"]
}
},
axis: {
x: {
tick: {
values: labels,
rotate: 90,
},
type: "category",
}
},
bindto: "#book-title-histogram",
});
By uncommenting x: "title" it leads to the plot to no longer be visible. With that line commented out, the axis is simply blank.
EDIT: bookData is an array with each element having keys count and title
Looks like mapping your data works.
const bookData = [{
count: 3,
title: 'The Foutainhead'
},{
count: 4,
title: 'Fight Club'
},{
count: 2,
title: 'Ender\'s Game'
}]
const titles = bookData.map((obj) => {
return obj.title
})
const counts = bookData.map((obj) => {
return obj.count
})
console.log(titles)
const chart = c3.generate({
data: {
x: 'title',
y: 'count',
json: {
title: titles,
data: counts,
},
type: "bar",
},
axis: {
x: {
tick: {
count: bookData.length,
rotate: 45,
},
type: "category",
}
},
bindto: "#book-title-histogram",
});

How to wrap this behavior in a plugin?

Currently I have a request to have a Bullet Chart with two targets (min and max).
To do it I am simply using a normal Bullet Chart with a Scatter series to draw the other target. I would like to wrap this behavior inside the bullet chart, so it would have something like the following options:
series: [{
data: [{
y: 275,
target: 250,
minTarget: 100
}]
},
And then, on the wrap, I would get this minTarget and make a scatter plot automatically. How can I do it?
Here's the fiddle I have so far: http://jsfiddle.net/gwkxd02p/
I do not think that render is a good method to add another series - anyway, you can try to do it like this:
Highcharts.wrap(Highcharts.seriesTypes.bullet.prototype, 'render', function(p) {
if (!this.hasRendered) {
const scatterData = this.points
.map(({ x, y, options }) => ({
x,
y: options.minTarget !== undefined ? options.minTarget : null
}))
if (scatterData.length) {
const scatter = this.chart.addSeries({
type: 'scatter',
data: scatterData,
marker: {
symbol: 'line',
lineWidth: 3,
radius: 8,
lineColor: '#000'
}
}, false)
scatter.translate()
scatter.render()
}
}
p.call(this)
})
And data for bullet:
series: [{
data: [{
y: 275,
target: 250,
minTarget: 100
}, {
y: 100,
target: 50
}, {
y: 500,
target: 600,
minTarget: 20
}]
live example: http://jsfiddle.net/n4p0ezzw/
I think that the better place is bullet's init method but in that method the points do not exist yet - so you would have to match the x values (if it is needed) on your own.
My suggestion is - do not wrap Highcharts if you don't have to. A better (simpler, safer, cleaner, easier to debug, it does not change Highcharts internal code) practice would be to wrap the Highcharts constructor in a function and parse the options inside it and then call the chart constructor with new options, like this:
function customBullet(container, options) {
const newOptions = {} // parse options, check for minTarget, etc. and create new options
return Highcharts.chart(container, newOptions)
}

How to plot two plots in the same figure in plotly.js

I want to plot 2 plots in the same figure using plotly.js. I have gone through the documentation of plotly.js but was unable to find it. Can any body help?
Here is the code snippet:
First Plot:
var data4 = [ {
z: z,
x: x,
y: y,
type: 'contour'
}
];
var layout = {
title: 'Simple Contour Plot'
}
Plotly.newPlot('visualization2', data4, layout);
Second Plot:
var trace = {
x: x11,
y: x21,
mode: 'lines+markers'
};
var data3 = [ trace];
var layout = {
title:'Line and Scatter Plot',
height: 400,
width: 480
};
Plotly.newPlot('visualization3', data3, layout);
I want to plot these two in one figure. Note: The first one is a contour plot and the second one is a Line plot.
You have the ability to put a number of traces into your data that you wish to plot and it will plot them.
You also can only have 1 title per graph, however, you can have multiple axis titles.
var firstPlotTrace = {
z: z,
x: x,
y: y,
type: 'contour'
name: 'yaxis data'
};
var secondPlotTrace = {
x: x11,
y: x21,
mode: 'lines+markers'
name: 'yaxis2 data'
};
var plotData = [firstPlotTrace, secondPlotTrace];
var layout = {
title: 'Double Plot Title',
height: 400,
width: 400,
yaxis: {title: 'Simple Contour Plot Axis', range: [-20, 20]}
yaxis2: {title: 'Line and Scatter Plot Axis', range: [-20, 20]}
};
Plotly.newPlot('plotDiv', plotData, layout);
HTML -
<div id="plotDiv" style="height: 400px; width: 400px;"></div>

Categories

Resources