ChartJS x-axis show only months of year - javascript

So I'm making this mobile app using Cordova, which allows me to use HTML, CSS and JavaScript. I'm currently using SQLite as a database (works almost same as mySQL) but that isn't that important. All I do is get my data from that database. I get both the date (of when the data was added to the Database) and the weight of a person.
I'm using a linegraph which show the weight on the Y-axis and the data on the X-axis.
What I want to do is only show the months as labels on the x-axis but still make it so that it show data for each day seperate. So for example if I add data on the 1st of January, the 2nd of January and the 3rd of January. I want to be able to see all 3 days as dots on my graph but on the X-axis it should only say 'January'.
I've been looking into the 'time' option of Chart.JS but can't really make any sense of how I'm supposed to do it.
HTML:
<canvas id="myChart" style="margin-top: 20px;"></canvas>
JavaScript:
//these are the arrays that I will fill dynamically. Labels will be my months and data will be the weight
var labels = [];
var data = [];
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: labels,
datasets: [{
backgroundColor: 'rgba(255, 119, 0, 0.5)',
borderColor: 'rgba(255, 119, 0, 1)',
data: data
}]
},
// Configuration options go here
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});

Use the time-type in your x-axis. With time: { unit: 'month' } (always months) or minUnit (months and years if necessary) you can get the month labels.
As label for your data you need to pass a Date or moment
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month'
}
}],
}
Here is a complete example.
Check the moment docs for dates, especially the creation and parsing of dates. Chart.js works with moment dates so it's quite important (and quite easy btw).

Related

How to set custom scale to polar area chart?

The Problem:
I am using polar area chart. For slices in this chart, each value after the largest value should appear one level smaller. The level is as follows: for example, if the value after a 38 slice is 6, it should look like 37. Or I should be able to set it to the level I want. My question is all about sizing the slices on the polar area.
What I get:
What I want:
Sorry for my bad drawing. You can think what i want is like:
scaling very small slices close to large slice.
Methods I tried:
I tried changing the scale and ticks parameters from the link chartjs axes settings but without success.
I put the index data after sorting the array as data into the dataset. It worked as I wanted, but this time the values appeared as index values.
Charts.js polar area scales I tried this also but not worked.
A solution can be reached from the two methods I tried, but I could not.
Code example here:
function SetWorkflowChart(labels, datas, labelColors) {
//label colors
// workflow stats chart
const workflowdata = {
labels: labels,
datasets: [{
normalized: true,
data: datas, // example data: [38, 5,3]
backgroundColor: labelColors,
borderColor: "rgba(0, 0, 0, 0.0)"
}]
};
const workflowconfig = {
type: 'polarArea',
data: workflowdata,
options: {
scales: {
r: {
grid: {
display: false
},
ticks: {
display: false //try2 i tried to set ticks for scale
},
suggestedMin: 5, //try1
suggestedMax: 20,//try1
}
},
plugins: {
legend: {
display: false,
position: "right"
},
},
responsive: false
}
};
workflowChart = new Chart(
document.getElementById('WorkFlowStatsChart'),
workflowconfig
);
}
I'll be pleased if you pay attention.

ChartJS date formating

I am trying to make a graph that shows how much power solarpanels are produsing using chartJS. I am using data in the following format
{x: Fri Mar 19 2021 06:20:28 GMT+0100 (centraleuropeisk normaltid), y: 1.88}
And it makes a graph but the x values is not in a readable date format. The graph liks like this:
Link to picture of graph (I am not allowed to post images yet apparently)
https://i.imgur.com/HUOHoqg.png
To make the graph I use this code:
var ctx = document.getElementById("lineChart");
var line = new Chart(ctx, {
type: "scatter",
data: {
datasets: [
{
data: power,
borderColor: "#ffd420",
showLine: true,
fill: false,
},
],
},
options: {
tooltips: { enabled: false },
hover: { mode: null },
elements: {
point: {
radius: 0,
},
},
//---
xAxes: [],
//--
},
});
I have tried to play with the xAxes settings but it still show a large number instead of a date.
Does anyone know what settings can fix this or do I need to change the format of the input?
I have searched alot but I can't find a solution to this problem.
There are 2 options, you can make use of the timescale provided by chart.js in here you can set what format you want it to show the dates: https://www.chartjs.org/docs/latest/axes/cartesian/time.html
The other options is to use the tick callback to do it yourself like this:
options: {
scales: {
xAxes: [{
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
const date = new Date(value)
return `${date.getDate()}/${date.getMonth()}/${date.getFullYear()}`
}
}
}]
}
}

Stacked bar chart with chartjs with included values

I am trying to create a visitors bar chart with included values, for example:
I want to show a bar chart of total daily visitors, and that bar should contain info of total visitors and first time visitors.
so data for a bar should look like:
data: {
labels: getDataAttributes(data, 'data-date'),
// an array holding the date of each bar (custom function)
// for example purposes lets say its just 3 bars
datasets: [{
label: ['Number of visitors', 'Number of new visitors'],
data: [[20,15], [25,10], [30, 15]],
// Here if we would use a simple stacked bar chart the height would be the sum of 2 values
// e.g.(20+15=35), but I wish that the bar height would be the number of total visitors 20
// the tooltip should contain values of total visitors and new visitors respectively 20 and 15
}]
}
I looked in the chartjs documentation, but found only examples with stacked values and that solution is not applied in my desired design, can someone please reference documentation/articles/tutorials or personal experience or perhaps I should switch to d3js? Thanks.
You could define two datasets, the first one would contain the values of new visitors, the second one the values of all visitors.
Then you would define the x-axis as being stacked:
options: {
scales: {
xAxes: [{
stacked: true
}],
Please take a look at below runnable code snippet to see how it works:
const baseData = [[20,15], [25,10], [30, 15]];
new Chart('chart', {
type: 'bar',
data: {
labels: ['25.10.2020', '26.10.2020', '27.10.2020'],
datasets: [{
label: 'Number of new visitors',
data: baseData.map(v => v[1]),
backgroundColor: 'green'
},
{
label: 'Number of visitors',
data: baseData.map(v => v[0]),
backgroundColor: 'blue'
}]
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="100"></canvas>

Plot Ranged horizontal bar graph with holes using ChartJS

I already have a graph using chartJS as shown below and the code for that is :
r_chart_data = [[-0.001, 2.052],[-2.385, 2.052]];
dr_chart_data = [[-0.01, 1.83],[1.05, 2.83],[1.05, 2.83]];
myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: label,
datasets: [{
label : 'DataSet1',
data: r_chart_data,
backgroundColor: 'rgb(255, 99, 132)'
},
{
label : 'DataSet2',
data: dr_chart_data,
backgroundColor: 'lightblue'
}
]
},
options: {
lineAtIndex : level,
scales: {
xAxes: [{
ticks: {
min: -5,
max: 5,
stepSize: 0.5,
}
}]
}
}
});
But what if my
r_chart_data[0] i.e. [-0.001,2.052]
is not a continuos range and instead its value is something like
[[-0.001,1.023],[1.5,2.052]]
then how should I plot the graph. Modified r_chart_data:
r_chart_data = [[[-0.001,1.023],[1.5,2.052]],[-2.385, 2.052]];
Similarly if I have a range of data sets that I need to plot in the form of a horizontal bar graph using ChartJS. The data set which are in the form of:
dataset1: [[-10,-4],[-2,2],[4,6]] // should be plotted in a single bar graph
dataset2: [[-2,1],[1.5,3.5],[5.2,8.9]] //should be plotted in a second bar
dataset3: [[2,4],[5,7]] //third bar
.. and so on
Moreover, each dataset need not have three range items. It can have one, two or any number of range items.

Why the draggable plugin does not work for a radar chart in ChartJS?

Currently I am building a frontend application, that uses data like AirQuality and information about POIs. For displaying the rating of the single points I am using a radar chart with ChartJS (using it the First Time ever!).
I can already change the chart with input data, that is pushed to the chart after a button click. Another functionality I wanted to implement is the possibility to drag the endpoints of the radar chart to change the values.
I found the draggable plugin and I have tried to implement it, but it does not work like I thought it would.
This is the first time I am working with chartJS and I have found myself confused with the documentation about the plugin.
I am using plain JavaScript. No frameworks at all.
Here is the code for my chart:
var data = {
labels: ["Air", "POI", "Noise"],
datasets: [{
backgroundColor: "#50237f",
borderColor: "#50237f",
data: [33.3333333333, 33.3333333333, 33.3333333333],
label: 'Rating'
}]
};
var options = {
scale: {
ticks: {
min: 0,
max: 100,
stepSize: 25,
showLabelBackdrop: false
}
},
maintainAspectRatio: true,
spanGaps: false,
elements: {
line: {
tension: 0.000001
}
},
};
var ctx = document.getElementById("ratingChart");
var myChart = new Chart(ctx, {
type: 'radar',
data: data,
options: options,
config: {
plugins: {
// maybe set the plugin here? but how?
}
}
});

Categories

Resources