Display ChartJS Data only when X is bigger than - javascript

I am trying to display data in a line chart from ChartJS, but my goal is to show only values after a specific year.
data: [
{
year: '1750',
value: 237.4646065136893,
},
{
year: '1755',
value: 275.8525403240655,
},
{
year: '1760',
value: 306.9496192507874,
},
{
year: '1790',
value: 330,
},
]
And I just want to show data later than 1755. My options scales config is the one below:
scales: {
xAxes: [
{
type: 'time',
time: {
format: 'YYYY',
stepSize: 5,
},
},
],
},
Do you know if there is a way to set some minX >= "1750"

You can filter the data and use the filtered data to feed the chart.
With Array.prototype.filter:
var newData = data.filter(function (el) {
return el.year >= 1755
});

Related

label on the x-axis does not show completely in Chart.js

I have a data from the backend(flask-sqlalchemy with mysql) in which data contains date in integer for week, month and year that looks like this:
in this case the x represents the week of the year:
let month_true = [
{
bob: {
"base-certificate": 60,
"case-certificate": 1,
"standard-certificate": 7,
},
x: 9,
},
{
bob: {
"base-certificate": 30,
"case-certificate": 4,
"standard-certificate": 5,
},
x: 11,
},
];
The first thing I did was to map the data and change the x into a readable format for Javascript and chart.js, using a function that converts week of the year number to actual date:
the function:
function getDateOfWeek(w, y) {
var d = 1 + (w - 1) * 7; // 1st of January + 7 days for each week
return new Date(y, 0, d);
}
Mapping through the data:
let newData = month_true.map(function (m) {
let dateObject = new Date();
let year = dateObject.getFullYear();
const weekDate = getDateOfWeek(m.x, year);
let r = new Date(Date.parse(weekDate));
const newd = {
x: r.setHours(0, 0, 0, 0),
base: m.bob["base-certificate"],
case: m.bob["case-certificate"],
standard: m.bob["standard-certificate"],
};
return newd;
});
let newdate = newData.map(function (d) {
return d.x;
});
now construct the chart:
let ctx = document.getElementById("chart").getContext("2d");
let config = {
//labels: newdate,
type: "bar",
data: {
datasets: [
{
label: "base",
data: newData,
parsing: {
xAxisKey: "x",
yAxisKey: "base",
},
},
{
label: "Case",
data: newData,
parsing: {
xAxisKey: "x",
yAxisKey: "case",
},
},
{
label: "Standard",
data: newData,
parsing: {
xAxisKey: "x",
yAxisKey: "standard",
},
},
],
},
options: {
scales: {
x: {
ticks: {
beginAtZero: true,
},
offset: true,
type: "time",
time: {
//isoWeekday: true,
unit: "week",
},
},
},
},
};
let myChart = new Chart(ctx, config);
It got plotted but the x-axis is not showing the second label:
enter image description here
what can I can do tomake the labels appear completely?
This is because by default the time scale auto generates ticks, if you dont want to include the labels from your data you need to set ticks.source to data:
options: {
scales: {
x: {
type: 'time',
ticks: {
source: 'data'
}
}
}
}

Accessing data from the callback function of a bar chart using chart js

I am currently trying to show a text stocked in the data in the tooltip, I can#t figure how to make it work, I have tried many things.
You can find below an example of what I#m trying to do, I want that the "text" value is displayed when hovering one of the bar.
I tried this
let data = [{
label: 'Available',
backgroundColor: '#3366ff',
data: [500],
text : "test1"
}, {
label: 'Budget',
backgroundColor: '#009999',
data: [5000, 6500],
text : "test2"
}, {
label: 'Actual',
backgroundColor: '#92d400',
data: [5200, 7245],
text : "test3"
}];
new Chart(document.getElementById("bar-chart-horizontal"), {
type: 'horizontalBar',
data: {
labels: ["Rooms", "Guests"],
datasets: data,
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var item = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return item.text;
}
}
}
}
});
But this is not working, it is not even displaying anything logical, only "Room" and "Guests".
What should I do to retrieve the correct informations ? I tried doing it like this : Fiddle
But it doesn't work when applied to my code... I'm probably missing something pretty stupid but I can't figure what.
Thanks to all the people that will read this and try to help me.
You just need to update the version of chart.js you are using to the latest V2 version since V3 has breaking changes.
Also you need to specify the x for the number for a horizontalBar instead of a y in both the dataset and the tooltip callback:
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['2017/06/12', '2017/06/23', '2017/07/12', '2017/07/23', '2017/08/12', '2017/08/23', '2017/09/12'],
datasets: [{
label: 'Values',
data: [{
x: 12,
value: 12,
text: "test1"
},
{
x: 3,
value: 13,
text: "test2"
},
{
x: 1,
value: 15,
text: "test3"
},
{
x: -3,
value: 5,
text: "test4"
},
{
x: 67,
value: 18,
text: "test5"
},
{
x: 12,
value: 11,
text: "test6"
},
{
x: 13,
value: 19,
text: "test7"
}
],
fill: false,
borderWidth: 2
}]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var item = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return item.x + ' ' + item.value + item.text;
}
}
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
This should work:
...
options: {
tooltips: {
callbacks: {
label: (context, data) => data.datasets[context.datasetIndex].data[context.index].text
}
}
...
jsfiddle

How can I change start week day on a graph? (plotly.js)

How can I change start week day on a graph? Now I have only Sundays on xaxis. I need to display only Mondays on xaxis. Thank you. My plotly config is:
...
xaxis: {
type: 'date',
automargin: true,
tickformat: '%d.%m',
maxPadding: 1,
},
yaxis: {
tickmode: 'array',
automargin: true,
showticklabels: false,
showgrid: false,
},
...
I cloned their repo and used your data array As I mentioned in my notes, it's just a matter of formatting what you're feeding your x/axis, I used moment in my example below, I'm sure you can use other ways to get the date format you'd like.
let me know if something about below code needs further clarification. BTW. I'm using react version, but at a quick glance they both looked like the same setup.
const PlotlyClass = (props) => {
let VasilyBasicArray = [{ value: "2020-04-16", count: 100 }, { value: "2020-04-17", count: 200 }, { value: "2020-04-18", count: 300 }, { value: "2020-04-19", count: 400 }, { value: "2020-04-20", count: 500 }, { value: "2020-04-21", count: 600 }, { value: "2020-04-22", count: 700 }, { value: "2020-04-23", count: 800 }, { value: "2020-04-24", count: 100 }, { value: "2020-04-25", count: 200 }, { value: "2020-04-26", count: 300 }, { value: "2020-04-27", count: 400 }, { value: "2020-04-28", count: 500 }, { value: "2020-04-29", count: 600 }, { value: "2020-04-30", count: 700 }]
return (
<Plot
data={[
{
x: VasilyBasicArray.map(rec => moment(rec.value).format('dd-Do')),
y: VasilyBasicArray.map(rec => rec.count),
type: 'scatter',
mode: 'lines+markers',
marker: { color: 'red' },
},
{ type: 'bar', x: VasilyBasicArray.map(rec => moment(rec.value).format('dd-Do')), y: VasilyBasicArray.map(rec => rec.count) },
]}
layout={{ width: 320, height: 240, title: 'A Fancy Plot' }}
/>
);
};
Make a local copy of plotly.
Find text: GregorianCalendar.prototype (or your default calendar).
In this prototype find variable firstDay (there are many firstDay variables in the file) and change value from 0 to 1.
This is not clean solution but it works if you don't need to use other languages.
In this prototype you can rename months and days too if you need.

Chart to multiply data series without date data

I tried to customize a highstock chart for data series without date data.
series: [{ name: "nameA", data: [value1, value2, ... valueN]}, {...}]
Is there a way to build highstock chart like this without date data (only for value) with enabled rangeSelector.selected settings.
Also, I need to have buttons for different ranges with no date values.
If you use highstock.js source code and chart constructor, you will be able to create basic chart with highstock features:
Highcharts.chart('container', {
series: [{
data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}],
rangeSelector: {
enabled: true,
inputDateFormat: '%H:%M:%S.%L',
inputEditDateFormat: '%H:%M:%S.%L',
// Custom parser to parse the %H:%M:%S.%L format
inputDateParser: function(value) {
value = value.split(/[:\.]/);
return Date.UTC(
1970,
0,
1,
parseInt(value[0], 10),
parseInt(value[1], 10),
parseInt(value[2], 10),
parseInt(value[3], 10)
);
}
},
navigator: {
enabled: true
},
scrollbar: {
enabled: true
}
});
Live demo: http://jsfiddle.net/BlackLabel/h1yudspa/
answer on my question from comments is provided by ppotaczek:
navigator and rangeSelector based on time, so you have two options. You can use milliseconds as a basic numeric time value or create your own rangeSelecgor and change navigator axis type in Highcharts core: example
I chose a variant with ms, and set next options:
rangeSelector: {
buttons: [{
type: 'millisecond',
count: 10,
text: '10'
},{
type: 'millisecond',
count: 50,
text: '50'
},{
type: 'all',
text: 'All'
}]
},
...
navigator: {
xAxis: {
labels: {
formatter: function () {
return this.value;
}
}
}
},
...
xAxis: {
labels: {
format: '{value}'
},
},
...
series: [{data: [[0, value0], [1, value1]], ... [n, valueN]}]

How to feed hour and minute data into chartJS

I'm trying to make a line chart using Chart.js. My data is of the form:
var result = [{x:"18:00",y:"230"},{x:"19:00",y:"232"},{x:"20:00",y:"236"},{x:"22:00",y:"228"}];
Where x represents the time with hours and minutes. I fed the data like this
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","21:00","22:00","23:00","24:00"],
datasets: [{
label: 'Voltage Fluctuation',
data: result,
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
position: 'bottom',
unit: 'minute',
time: {
displayFormats: {
hour: 'HH:mm'
}
}
}],
},
}
});
And I'm getting an empty chart. Where am I going wrong? I feel I'm doing something wrong with my labels since they don't show up on the chart but I don't understand how. Is there any way I can feed datalabels with momentjs?
You cannot just pass the result array to data, as it isn't in correct format. data property expects an array of numbers. So, you need to parse the labels (using moment.js) and data from result array before using them for the chart.
Here is how labels and data should be parsed from the result array and fed to the chart :
var result = [{ x: "18:00", y: "230" }, { x: "19:00", y: "232" }, { x: "20:00", y: "236" }, { x: "22:00", y: "228" }];
// parse labels and data
var labels = result.map(e => moment(e.x, 'HH:mm'));
var data = result.map(e => +e.y);
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Voltage Fluctuation',
data: data,
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'hour',
displayFormats: {
hour: 'HH:mm'
}
}
}]
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>

Categories