Vertical stacking of line plots using ChartJs library sharing same x axis - javascript

I want to have three LineCharts below each other. They are sharing same x-axis (time). I was able to create this:
However, it is very useless to have x-axis on the top and middle chart. I would prefer not to display the x-axis for the top and middle. When I tried it, I got this:
But as you can see, the last grid for 12AM is not visible for the top and middle chart, and the grids are not aligned (it looks weird). Each chart is rendered as a separate component using React.
Here are my TimelinePlot component which is rendering each LineChart (sorry for the mess, but I did not yet refactor it):
import React from 'react';
import { Line } from 'react-chartjs-2';
import { GetColors } from '../../utils/PlotDescriptionHelper';
class TimelinePlot extends React.Component {
MapPropsToData(props) {
const colors = GetColors(props.series.length);
return props.series.map((dataset, index) => {
return {
label: dataset.name,
data: dataset.data,
borderWidth: 1,
fill: false,
borderColor: colors[index],
//pointBackgroundColor: 'rgb(255,255,255)',
};
});
}
MapPropsToOptions(props) {
return {
elements: {
point: {
radius: 0,
},
},
legend: {
// display: props.showLegend,
position: 'top',
align: 'end',
},
scales: {
yAxes: [
{
ticks: props.yAxisTicks,
scaleLabel: {
display: true,
labelString: props.yAxisName + props.yAxisUnit,
},
},
],
xAxes: [
{
type: 'time',
// position: props.xAxisPosition,
time: {
parser: 'YYYY-MM-DD HH:mm',
tooltipFormat: 'll HH:mm',
},
// scaleLabel: {
// display: true,
// //labelString: 'Date',
// },
ticks: {
min: props.xAxisStart,
max: props.xAxisEnd,
//display: true,
display: props.xAxisDisplay,
},
},
],
},
};
}
render() {
const dataset = { datasets: this.MapPropsToData(this.props) };
return (
<div className='measurement-row'>
<Line
data={dataset}
options={this.MapPropsToOptions(this.props)}
position='absolute'
height='15%'
width='80%'
/>
</div>
);
}
}
And here is the render method of the parent using TimelinePlot component:
render() {
var plots = Object.keys(this.state.timeSeries).map((key, index) => {
return (
<TimelinePlot
key={key + index}
series={this.state.timeSeries[key]}
yAxisName={FirstLetterToUpper(key)}
yAxisUnit={MapKeyToUnit(key)}
xAxisDisplay={index === Object.keys(this.state.timeSeries).length - 1}
xAxisPosition={index === 0 ? 'top' : 'bottom'}
xAxisStart={this.state.startTime}
xAxisEnd={this.state.endTime}
showLegend={index === 0}
yAxisTicks={MapYAxisTicks(key)}
/>
);
});
return (
<div className='width-90'>
<TimelineDashboardHeader />
<div className='dashboard__column'>{plots}</div>
</div>
);
}

Related

ChartJS: Disable animation only for y-axis

I currently have a chart that shows real-time information. I tried to disable the animation for the y-axis, because the dots hopped around along the y-axis which creates a weird effect. But I still want that new dots fade in smoothly along the x-axis.
I tried it with this configuration:
const chartOptions: ChartOptions = {
animations: {
x: {
duration: 500
},
y: false,
},
// ...
};
The result is no animation at all. Not on the y-axis, but also not on the x-axis. It doesn't look smooth anymore.
And after 25 data points I shift()/push(newDataPoint) in a separate array and then replace the whole data array for the chart as I use ChartJS with the vue-chartjs library.
I need the exact same behavior like in the GIF above, except that it should not stutter but scrolling smooth along the x-axis.
Whole vue-chartjs example for reference
<script setup lang="ts">
const chartData = ref<ChartData<'line'>>({
labels: [],
datasets: []
})
const chartLabels: string[] = Array(maxDataPoints).fill('');
const chartDataPoints: number[] = Array(maxDataPoints).fill(18.3);
function fillData() {
if (chartDataPoints.length > maxDataPoints) {
chartLabels.shift();
chartDataPoints.shift();
}
chartLabels.push(new Date().toLocaleString())
chartDataPoints.push(Number((currentDistance.value * 0.1).toFixed(1)))
const updatedChartData: ChartData<'line'> = {
labels: [...chartLabels],
datasets: [
{
label: 'Distance',
tension: 0.5,
data: [...chartDataPoints],
}
]
}
chartData.value = { ...updatedChartData }
}
onMounted(() => {
fillData();
setInterval(() => fillData(), 500)
})
const chartOptions: ChartOptions = {
responsive: true,
maintainAspectRatio: false,
//animation: false,
animations: {
x: {
duration: 500
},
y: false,
},
scales:{
x: {
display: false,
},
y: {
suggestedMin: 0,
suggestedMax: 20,
}
},
plugins: {
legend: {
display: false
},
},
}
</script>
<template>
<LineChart :chartData="chartData" :chartOptions="chartOptions" />
</template>
In the end I used the chartjs-streaming-plugin by nagix which does exactly what I was looking for.

How to increase line chart width in ng2-charts?

I am trying to render a line chart using "ng2-charts": "^2.3.0" and "chart.js": "^2.8.0",. Chart is displaying as expected but only problem is that I am not able to increase the line width with borderWidth property.
Code:
import { SingleDataSet, Label, Color } from "ng2-charts";
import { ChartType, ChartOptions } from "chart.js";
public barChartType1: ChartType = "line";
public lineChartOptions: ChartOptions = {
responsive: true,
legend: { display: false },
scales: {
yAxes: [
{
display: false,
ticks: {
beginAtZero: false
},
scaleLabel: {
display: true,
labelString: '',
fontSize: 20,
}
},
]
},
elements: {
point:{
radius: 0,
borderWidth: 50
}
},
};
public lineChartColors: Color[] = [
{
borderColor: '#5081bd',
backgroundColor: 'transparent',
},
];
Template:
<canvas baseChart height="30vh" width="80vw"
[colors]="lineChartColors"
[datasets]="barChartDataSets1[customdata.index]"
[labels]="barChartLabels1[customdata.index]"
[options]="lineChartOptions"
[chartType]="barChartType1"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)">
</canvas>
Inputs:
barChartDataSets1 [{"data":["2.00","2.00","2.00","2.00","2.00","2.00","2.00","2.00"]
barChartLabels1 [" "," "," ","ans1"," "," "," ","ans2"]
Output:
Is there any solution for this and why changing borderWidth property isn't working on it?
This is because you placed the option in the wrong namespace instead of using options.elements.point you need to place it in options.elements.line:
elements: {
point: {
radius: 0,
},
line: {
borderWidth: 8
}
},

Chart.js legend configuration options not working [duplicate]

I am trying to hide the legend of my chart created with Chart.js.
According to the official documentation (https://www.chartjs.org/docs/latest/configuration/legend.html), to hide the legend, the display property of the options.display object must be set to false.
I have tried to do it in the following way:
const options = {
legend: {
display: false,
}
};
But it doesn't work, my legend is still there. I even tried this other way, but unfortunately, without success.
const options = {
legend: {
display: false,
labels: {
display: false
}
}
}
};
This is my full code.
import React, { useEffect, useState } from 'react';
import { Line } from "react-chartjs-2";
import numeral from 'numeral';
const options = {
legend: {
display: false,
},
elements: {
point: {
radius: 1,
},
},
maintainAspectRatio: false,
tooltips: {
mode: "index",
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
return numeral(tooltipItem.value).format("+0,000");
},
},
},
scales: {
xAxes: [
{
type: "time",
time: {
format: "DD/MM/YY",
tooltipFormat: "ll",
},
},
],
yAxes: [
{
gridLines: {
display: false,
},
ticks: {
callback: function(value, index, values) {
return numeral(value).format("0a");
},
},
},
],
},
};
const buildChartData = (data, casesType = "cases") => {
let chartData = [];
let lastDataPoint;
for(let date in data.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data[casesType][date] - lastDataPoint
}
chartData.push(newDataPoint);
}
lastDataPoint = data[casesType][date];
}
return chartData;
};
function LineGraph({ casesType }) {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async() => {
await fetch("https://disease.sh/v3/covid-19/historical/all?lastdays=120")
.then ((response) => {
return response.json();
})
.then((data) => {
let chartData = buildChartData(data, casesType);
setData(chartData);
});
};
fetchData();
}, [casesType]);
return (
<div>
{data?.length > 0 && (
<Line
data={{
datasets: [
{
backgroundColor: "rgba(204, 16, 52, 0.5)",
borderColor: "#CC1034",
data: data
},
],
}}
options={options}
/>
)}
</div>
);
}
export default LineGraph;
Could someone help me? Thank you in advance!
PD: Maybe is useful to try to find a solution, but I get 'undefined' in the text of my legend and when I try to change the text like this, the text legend still appearing as 'Undefindex'.
const options = {
legend: {
display: true,
text: 'Hello!'
}
};
As described in the documentation you linked the namespace where the legend is configured is: options.plugins.legend, if you put it there it will work:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}
]
},
options: {
plugins: {
legend: {
display: false
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>
On another note, a big part of your options object is wrong, its in V2 syntax while you are using v3, please take a look at the migration guide
Reason why you get undefined as text in your legend is, is because you dont supply any label argument in your dataset.
in the newest versions this code works fine
const options = {
plugins: {
legend: {
display: false,
},
},
};
return <Doughnut data={data} options={options} />;
Import your options value inside the charts component like so:
const options = {
legend: {
display: false
}
};
<Line data={data} options={options} />

Vue Chart JS options aren't used

I'm using Vue Chart JS v3.5.1 in my Nuxt JS/Vue project, and I've noticed that when trying to use options and pass them as a prop, nothing happens, the chart defaults back to the chart's default settings despite me overwriting settings.
I've got several files:
plugins/LineChart.js
components/LineChart.vue
plugins/LineChart.js
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins
export default {
extends: Line,
mixins: [reactiveProp],
computed: {
localOptions: function() {
return this.chartOptions
},
localData: function() {
console.log(`data: ${this.chartData}`)
return this.chartData
}
},
mounted () {
this.renderLineChart()
},
methods: {
/*
** Render a line chart
*/
renderLineChart () {
// this.chartdata is created in the mixin.
// If you want to pass options please create a local options object
this.renderChart(this.localData, this.localOptions)
}
},
watch: {
chartData: {
handler: function (val, oldVal) {
this._data._chart.destroy()
this.renderLineChart()
},
deep: true
},
chartOptions: {
handler: function (val, oldVal) {
this.localOptions = val
},
deep: true
}
}
}
components/LineChart.vue
<template>
<div>
<line-chart :chart-data="customChartData" :chart-options="customChartOptions" class="data-chart"></line-chart>
</div>
</template>
<style>
.data-chart canvas {
width: 100% !important;
height: auto !important;
}
</style>
<script>
import LineChart from '~/plugins/LineChart.js'
export default {
components: {
LineChart
},
props: {
labels: {
type: Array,
default: null
},
datasets: {
type: Array,
default: null
},
options: {
type: Object,
default: () => ({})
}
},
data () {
return {
customChartData: {},
customChartOptions: {}
}
},
mounted () {
this.fillData()
},
methods: {
fillData () {
this.customChartData = {
labels: this.labels,
datasets: this.datasets
}
this.customChartOptions = {
options: this.options
}
}
}
}
</script>
My usage, is then reasonably simple, yet I'm not getting my options to show?
<LineChart
:options="{
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
display: false
},
ticks: {
autoSkip: true,
maxTicksLimit: 3,
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
display: true,
gridLines: {
display: true,
color: '#f3f5f6'
}
}]
},
elements: {
point: {
radius: 0,
hitRadius: 35
}
}
}"
:labels="['test']"
:datasets="[{
fill: false,
borderWidth: 2.5,
pointBackgroundColor: '#fff',
borderColor: '#5046e5',
data: [500,
}]"
/>
What am I doing wrong?
UPDATE
In addition, I seem to only have the first chart out of many charts on the page show data, why would only one chart in a series of charts show data, I've got a key on each one.
in your fillData it looks like you assign the options wrong. Vue Chartjs expects an object with the options in it and not an object with an field options with the options.
If you change: this.customChartOptions = {options: this.options} to: this.customChartOptions = this.options it should work

how to Show value in pie chart Legend in react-chartjs-2

I'm using react-Chartjs-2 pie chart for my dashboard. as per the requirement I have to show both label with data in the legend. the below component which I'm using in my application
import React, { Component } from "react";
import { Doughnut } from "react-chartjs-2";
class DoughnutChart extends Component {
constructor(props) {
super(props);
}
render() {
const chartdata = {
labels: ["Newly Added", "Edited", "Deleted"],
datasets: [
{
label: "Markets Monitored",
backgroundColor: [
"#83ce83",
"#959595",
"#f96a5d",
"#00A6B4",
"#6800B4",
],
data: [9, 5, 3],
},
],
};
return (
<Doughnut
data={chartdata}
options={{
legend: { display: true, position: "right" },
datalabels: {
display: true,
color: "white",
},
tooltips: {
backgroundColor: "#5a6e7f",
},
}}
/>
);
}
}
export default DoughnutChart;
now I'm getting chart like given below
my output
my requirement is adding values in legend(customizing chart legend). example image expected output
One way to do it would be to define data and labels before creating the chart. Then you can add the data to labels using .map method.
import React, { Component } from "react";
import { Doughnut } from "react-chartjs-2";
class DoughnutChart extends Component {
constructor(props) {
super(props);
}
render() {
let data = [9, 5, 3]
let labels = ["Newly Added", "Edited", "Deleted"]
let customLabels = labels.map((label,index) =>`${label}: ${data[index]}`)
const chartdata = {
labels: customLabels,
datasets: [
{
label: "Markets Monitored",
backgroundColor: [
"#83ce83",
"#959595",
"#f96a5d",
"#00A6B4",
"#6800B4",
],
data: data,
},
],
};
return (
<Doughnut
data={chartdata}
options={{
legend: { display: true, position: "right" },
datalabels: {
display: true,
color: "white",
},
tooltips: {
backgroundColor: "#5a6e7f",
},
}}
/>
);
}
}
export default DoughnutChart;

Categories