chart.js d3js chart in time scale, data from CSV file - javascript

first, thanks a lot for all the help from stackoverflow.
I'm trying to display charts which have Data spreaded according to the amount of time between data points. https://www.chartjs.org/docs/latest/axes/cartesian/time.html
so: X Axis: ---2022-02-01-----------2022-02-05-----------2022-02-07----------
My object:
X Axis: ---2022-02-01-----------2022-02-03-----------2022-02-04-----------
but the challenge is that the datas are not coming from the HTML code with x and y like this:
data: [{
x: '2022-02-01',
y: 25
}, {
x: '2022-02-05',
y: -25
}, {
x: '2022-02-07',
y: -225
}]
but from a CSV file.
So i don't know how to set the xAxis scale config with time.
Please somebody know how to solve it?
Thanks a lot.
<script>
d3.csv("example.csv").then(makeChart);
function makeChart(players) {
var dateData = players.map(function (d) {
return d.date;
});
var btcData = players.map(function (d) {
return d.btc;
});
var VETData = players.map(function (d) {
return d.vet;
});
var totalData = players.map(function (d) {
return d.total;
});
var BTCColors = players.map(function(d) {
return d.btc < 0 ? '#F15F36' : '#19A0AA';
});
var VETColors = players.map(function(d) {
return d.vet < 0 ? '#F15F36' : '#19A0AA';
});
var TOTALColors = players.map(function(d) {
return d.total < 0 ? '#F15F36' : '#19A0AA';
});
var ctx = document.getElementById("myChart").getContext("2d");
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: dateData,
datasets: [{
type: 'bar',
label: 'BTCUSDT',
borderColor: BTCColors,
backgroundColor:BTCColors,
data: btcData
}, {
type: 'bar',
label: 'VETUSDT',
data: VETData,
borderColor: VETColors,
backgroundColor: VETColors
}, {
type: 'line',
label: 'TOTAL',
data: totalData,
borderColor: '#F15F36',
backgroundColor: '#19A0AA',
borderWidth : 1,
pointRadius : 1.1,
fill:false
}]
}
}
);
const config = {
type: 'scatter',
data: data,
options: {
scales: {
x: {
type: 'time',
time:{
unit:'day'
}
}
}
}
}
};
</script>
js src:
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"
integrity="sha512-d9xgZrVZpmmQlfonhQUvTR7lMPtO7NkZMkA0ABN3PHCbKA5nqylQ/yWlFAyY6hYgdF1Qh6nYiuADWwKB4C2WSw=="
crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
my csv file:
date,btc,vet,total
2022-02-01,25,0,25
2022-02-05,0,-50,-25
2022-02-07,-200,0,-225
2022-02-20,-0,100,-125
2022-03-01,0,150,25
2022-03-15,400,0,425
2022-04-01,-100,0,325
2022-04-15,0,-10,315
2022-06-01,500,0,815
2022-07-01,0,200,1015
chart preview

Okay i find the answer, had to convert the CSV into Arrays, and arrays into data structure:
<script>
drawChart();
async function drawChart(){
const dataArray = await getData();
const BTCdatapoints = dataArray.DATEdata.map((day,index) => {
let dayObject = {};
dayObject.x = dataArray.DATEdata[index];
dayObject.y = dataArray.BTCdata[index];
return dayObject
})
const VETdatapoints = dataArray.DATEdata.map((day,index) => {
let dayObject = {};
dayObject.x = dataArray.DATEdata[index];
dayObject.y = dataArray.VETdata[index];
return dayObject
})
const TOTALdatapoints = dataArray.DATEdata.map((day,index) => {
let dayObject = {};
dayObject.x = dataArray.DATEdata[index];
dayObject.y = dataArray.TOTALData[index];
return dayObject
})
const data = {datasets: [{
label: 'BTCUSDT',
data: BTCdatapoints
}, {
type: 'bar',
label: 'VETUSDT',
data: VETdatapoints
}, {
type: 'line',
label: 'TOTAL',
data: TOTALdatapoints
}]
}
const config = {
type: 'bar',
data,
options: {
scales: {
x: {
type: "time",
time: {
unit: "day"
}
},
y:{
beginAtZero : true
}
}
}
};
const myChart = new Chart(
document.getElementById("myChart"),
config
);
};
async function getData() {
const DATEdata = [];
const BTCdata = [];
const VETdata = [];
const TOTALData = [];
const url ='example.csv';
const response = await fetch(url);
const tabledata = await response.text();
const table = tabledata.split('\r\n').splice(1);
table.forEach(row =>{
const column = row.split(',');
const date = column[0];
const BTC = column[1];
const VET = column[2];
const TOTAL = column[3];
DATEdata.push(date);
BTCdata.push(BTC);
VETdata.push(VET);
TOTALData.push(TOTAL);
});
return {DATEdata,BTCdata,VETdata,TOTALData};
}
</script>
JS SRC:
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/papaparse#5.3.2/papaparse.min.js"></script>

Related

Display data for specific release selected in release filter at the top of page in rally dashboard

This is my code and in this the data displayed in chart is hole project data but in rally dashboard there is release filter at the top of your page. and i want my chart to show data of the the release selected by that filter and my sdk version in code is 1.33
<!DOCTYPE HTML\>
<script
src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js">
var WORKSPACE_OID = "__WORKSPACE_OID__";
var PROJECT_OID = "__PROJECT_OID__";
var PROJECT_SCOPING_UP = "__PROJECT_SCOPING_UP__";
var PROJECT_SCOPING_DOWN = "__PROJECT_SCOPING_DOWN__";
var MILS_IN_DAY = 86400000;
var DAYS_BACK = 30;
var filterChart;
var currentProjectDataSource;
var fromDate = new Date(new Date().getTime() - (MILS_IN_DAY * DAYS_BACK));
var allDefects = [];
// var currentRelease;
var onLoadAllIssues = function (result) {
// var defects = result.defects.filter(function (defect) {
// return defect.Release && defect.Release.\_refObjectName === currentRelease.Name;
// });
var labels = [];
var openDefects = [];
var closedDefects = [];
var defects = result.defects;
for (var count = 0; count < defects.length; count++) {
allDefects[allDefects.length] = defects[count];
var defect = defects[count];
labels.push(defect.CreationDate.split('T')[0]);
if (defect.ClosedDate !==null) {
closedDefects.push(defect.ClosedDate.split('T')[0]);
}
}
closedDefects.sort();
const counts = {};
labels.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
const closedcounts = {};
closedDefects.forEach(function (x) { closedcounts[x] = (closedcounts[x] || 0) + 1; });
mychart(counts,closedcounts,labels)
};
var createCharts = function () {
var loadAllDefectsQuery = {
type: 'defect',
key: 'defects',
fetch: 'CreationDate,ClosedDate,ObjectID,FormattedID,Name,State,Priority',
order: 'CreationDate',
query: '((CreationDate != "null") OR (CreationDate > "' + dojo.date.stamp.toISOString(fromDate, { zulu: true }) +
'"))'
};
currentProjectDataSource.findAll(loadAllDefectsQuery, onLoadAllIssues);
};
var initPage = function () {
currentProjectDataSource = new rally.sdk.data.RallyDataSource(WORKSPACE_OID, PROJECT_OID, PROJECT_SCOPING_UP,
PROJECT_SCOPING_DOWN);
createCharts();
};
rally.addOnLoad(initPage);
function mychart(counts,closedcounts,labels) {
const pielable = labels;
const piedata = counts;
const closedcountsdata = closedcounts;
const data = {
datasets: [
{
label: 'Number of opened defects',
data: piedata,
},
{
label: 'Number of closed defects',
data: closedcountsdata,
}
]
};
const config = {
type: 'line',
data: data,
options: {
scales: {
x: {
min:"2022-01-01",
max:"2022-12-31",
type: 'time',
time:{
unit:'day',
},
},
y: {
beginAtZero: true,
grace: 5,
ticks: {
stepSize: 1,
},
},
},
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Defect Burndown Chart'
},
tooltip: {
yAlign: 'bottom',
titleMarginBottom: 0,
callbacks: {
title: function (context) {
return( `${context[0].label.slice(0, -13).replace(/,/g, " ")}`)
},
}
}
}
}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
)
filterChart= function filterChart(date){
const year = date.value.substring(0,4);
const month = date.value.substring(5);
const lastday = (y,m)=>{
return new Date(y,m,0).getDate();
}
const startDate = `${date.value}-01`;
const endDate = `${date.value}-${lastday(year,month)}`;
myChart.config.options.scales.x.min=startDate;
myChart.config.options.scales.x.ma`your text`x=endDate;
myChart.update();
}}
</script>

How can I add a border to the columns on this graph.js

I've put together a graph which pulls data from google.
I'm trying to change the styling but can't find a way to do it through CSS. I want to add a border to both columns.
I couldunt add all the code, but I can see this is the part that mentions colors.
https://codepen.io/jameswill77/pen/WNzXxeJ
const colors = ['#FDF7F2', '#23F0C7'];
dataj = JSON.parse(data.toJSON());
console.log(dataj.cols[0].label);
const labels = [];
for (c = 1; c < dataj.cols.length; c++) {
if (dataj.cols[c].label != "") {
labels.push(dataj.cols[c].label);
}
}
console.log(labels);
const datasets = [];
for (i = 0; i < dataj.rows.length; i++) {
const series_data = [];
for (j = 1; j < dataj.rows[i].c.length; j++) {
if (dataj.rows[i].c[j] != null) {
if (dataj.rows[i].c[j].v != null) {
series_data.push(dataj.rows[i].c[j].v);
} else {
series_data.push(0);
}
}
}
var dataset = {
label: dataj.rows[i].c[0].v,
backgroundColor: colors[i],
borderColor: colors[i],
data: series_data
}
datasets.push(dataset);
}
console.log(datasets);
const chartdata = {
labels: labels,
datasets: datasets
};
var canvas = document.getElementById("myChart");
var setup = {
type: 'bar',
data: chartdata,
options: {
plugins: {
title: {
display: true,
text: dataj.cols[0].label
}
},
responsive: true,
}
}
chart = new Chart(canvas, setup);
}
added option borderWidth and changed value of borderColor in the datasets.
https://codepen.io/fver1004/pen/MWVOJpR?editors=1010
google.charts.load('current', {
'packages': ['corechart', 'bar']
});
google.charts.setOnLoadCallback(initChart);;
function initChart() {
URL = "https://docs.google.com/spreadsheets/d/1MV4chXniMBHj1ROAIf-BZR3LsoN-HT180pUwivU5Jbc/edit#gid=2112195720";
var query = new google.visualization.Query(URL);
query.setQuery('select *');
query.send(function(response) {
handleQueryResponse(response);
});
}
function handleQueryResponse(response) {
var data = response.getDataTable();
var columns = data.getNumberOfColumns();
var rows = data.getNumberOfRows();
// console.log(data.toJSON());
const colors = ['#eeeeee', '#23F0C7'];
const border_colors = ['#ececec', '#21DEC5'];
dataj = JSON.parse(data.toJSON());
// console.log(dataj.cols[0].label);
const labels = [];
for (c = 1; c < dataj.cols.length; c++) {
if (dataj.cols[c].label != "") {
labels.push(dataj.cols[c].label);
}
}
// console.log(labels);
const datasets = [];
for (i = 0; i < dataj.rows.length; i++) {
const series_data = [];
for (j = 1; j < dataj.rows[i].c.length; j++) {
if (dataj.rows[i].c[j] != null) {
if (dataj.rows[i].c[j].v != null) {
series_data.push(dataj.rows[i].c[j].v);
} else {
series_data.push(0);
}
}
}
var dataset = {
label: dataj.rows[i].c[0].v,
backgroundColor: colors[i],
borderColor: border_colors[i],
borderWidth: 4,
data: series_data
}
datasets.push(dataset);
}
console.log(datasets);
const chartdata = {
labels: labels,
datasets: datasets
};
var canvas = document.getElementById("myChart");
var setup = {
type: 'bar',
data: chartdata,
options: {
plugins: {
title: {
display: true,
text: dataj.cols[0].label
}
},
responsive: true,
}
}
chart = new Chart(canvas, setup);
}

how do i use the numbers i key in from a form as the input data for chartjs

i am trying to use my input data as the data of the graph
i am using chartjs
please help
iv tried to split and join the numbers but nothing is showing
i am using flask as my back end
var Diadata = []
function getdata() {
Diadata[0] = document.getElementById('Carat').value;
Diadata[1] = document.getElementById("Cut").value;
Diadata[2] = document.getElementById("Color").value;
Diadata[3] = document.getElementById("Clarity").value;
Diadata[4] = document.getElementById("Depth").value;
Diadata[5] = document.getElementById("Table").value;
Diadata[6] = document.getElementById("X").value;
Diadata[7] = document.getElementById("Y").value;
Diadata[8] = document.getElementById("Z").value;
console.log("TEST: ",[Diadata.join(" ").replace(/ /g,",")])
}
var ctxL = document.getElementById("barChartHorizontal").getContext('2d');
var myLineChart = new Chart(ctxL, {
type: 'horizontalBar',
data: {
labels: ["Carat", "Cut", "Color", "Clarity", "Depth", "Table", "X", "Y", "Z"],
datasets: [
{
label: "Price",
data: [Diadata.join(" ").replace(/ /g,",")], //i want to add my input data here
backgroundColor: 'orange',
borderWidth: 0,
}
]
},
The data array is expecting an array with values so if you remove your join it should work.
You would get this:
var Diadata = []
function getdata() {
Diadata[0] = document.getElementById('Carat').value;
Diadata[1] = document.getElementById("Cut").value;
Diadata[2] = document.getElementById("Color").value;
Diadata[3] = document.getElementById("Clarity").value;
Diadata[4] = document.getElementById("Depth").value;
Diadata[5] = document.getElementById("Table").value;
Diadata[6] = document.getElementById("X").value;
Diadata[7] = document.getElementById("Y").value;
Diadata[8] = document.getElementById("Z").value;
}
getdata();
var ctxL = document.getElementById("barChartHorizontal").getContext('2d');
var myLineChart = new Chart(ctxL, {
type: 'horizontalBar',
data: {
labels: ["Carat", "Cut", "Color", "Clarity", "Depth", "Table", "X", "Y", "Z"],
datasets: [
{
label: "Price",
data: Diadata, //i want to add my input data here
backgroundColor: 'orange',
borderWidth: 0,
}
]
},

Getting graphic data from DIV element

I using Chart.js and I want to pull the data from the properties inside the DIV element.
I can get data in data-gpget and data-gpret. It writes to the console but does not see it as "data" data.
data: getATT('#graph3','data-gpval') and data: getATT('#graph3','data-gpret')
What could be the reason for this? What am I missing?
Thank you.
<div id="graph3" data-gpget="[28,12,14,27,11]" data-gpret="[21,64,32,73,76]">
<canvas id="js-chartjs-earnings"></canvas>
</div>
JS:
function getATT(id,value) {
return $(id).attr(value);
}
return e = a, t = [{
key: "initCharts", value: function () {
Chart.defaults.scale.gridLines.color = "transparent", Chart.defaults.scale.gridLines.zeroLineColor = "transparent", Chart.defaults.scale.ticks.beginAtZero = !0, Chart.defaults.global.elements.line.borderWidth = 0, Chart.defaults.global.elements.point.radius = 0, Chart.defaults.global.elements.point.hoverRadius = 0, Chart.defaults.global.tooltips.cornerRadius = 3, Chart.defaults.global.legend.labels.boxWidth = 12;
var r, a = jQuery(".js-chartjs-earnings");
r = {
labels: ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"],
datasets: [{
label: "GETTING",
fill: !0,
data: getATT('#graph3','data-gpget')
}, {
label: "RETURNS",
fill: !0,
data: getATT('#graph3','data-gpret')
}]
}, a.length && new Chart(a, {
type: "bar",
data: r,
options: {
tooltips: {
intersect: !1, callbacks: {
label: function (r, a) {
return a.datasets[r.datasetIndex].label + ": $" + r.yLabel
}
}
}
}
})
}
}, {
key: "init", value: function () {
this.initCharts()
}
}], null && r(e.prototype, null), t && r(e, t), a
the attr method will always return a string.
try using the data method instead...
return $(id).data(value);
just be sure to remove the data- prefix from the attribute names.
see / run following example...
var testATT = getATT('#graph3','data-gpget');
var testData = getData('#graph3','gpget');
console.log(typeof testATT, testATT);
console.log(typeof testData, testData);
function getData(id,value) {
return $(id).data(value);
}
function getATT(id,value) {
return $(id).attr(value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="graph3" data-gpget="[28,12,14,27,11]" data-gpret="[21,64,32,73,76]">
<canvas id="js-chartjs-earnings"></canvas>
</div>

How do I change the colors on Y-Axis for values above, below zero? Chart.js 2.6

Using chart.js 2.6 Is there a way to dynamically change the bars in my chart for values above zero and below zero? The graph series data is being generated via a call to a method. Right now its just a random number generator but will be a DB call.
function changeWOWData(chart) {
var datasets = chart.data.datasets;
var labelLen = chart.data.labels.length;
if (datasets[0]) {
for (i = 0, len = datasets.length; i < len; i++) {
try {
for (j = 0, len = labelLen; j < len; j++) {
datasets[i].data[j] = getRandomInt(-100, 100);
}
} catch (e) {
console.log(e.message);
}
}
}
}
Chart looks like this:
I want the chart bars above zero to be blue, the bars below zero to be red.
Any/all replies appreciated. Thanks in advance!
Griff
** Edit ** Added the code from the answer below as such:
var myBarChart = new Chart(wowChart, {
type: 'bar',
data: wowData,
plugins: [{
beforeDraw: function (c) {
var data = c.data.datasets[0].data;
for (var i in data) {
try {
var bar = c.data.datasets[0]._meta[0].data[i]._model;
if (data[i] > 0) {
bar.backgroundColor = '#07C';
} else bar.backgroundColor = '#E82020';
} catch (ex) {
console.log(ex.message);
}
console.log(data[i]);
}
}
}],
options: wowOptions
});
Every other line of the console I see the data element along with the exception
You could accomplish that using the following chart plugin :
plugins: [{
beforeDraw: function(c) {
var data = c.data.datasets[0].data;
for (let i in data) {
let bar = c.data.datasets[0]._meta['0'].data[i]._model;
if (data[i] > 0) {
bar.backgroundColor = '#07C';
} else bar.backgroundColor = '#E82020';
}
}
}]
add this followed by your chart options
ᴅᴇᴍᴏ
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
datasets: [{
label: 'LEGEND',
data: [9, 14, -4, 15, -8, 10]
}]
},
options: {},
plugins: [{
beforeDraw: function(c) {
var data = c.data.datasets[0].data;
for (let i in data) {
let bar = c.data.datasets[0]._meta['0'].data[i]._model;
if (data[i] > 0) {
bar.backgroundColor = '#07C';
} else bar.backgroundColor = '#E82020';
}
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas" height="180"></canvas>
in chartjs v3 you can use Simply scriptable option
example:
datasets: [
{
data: this.chartData,
backgroundColor(context) {
const index = context.dataIndex
const value = context.dataset.data[index]
return value < 0 ? 'red' : 'blue'
}
}
]
visit https://www.chartjs.org/docs/latest/general/options.html#scriptable-options

Categories