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.
I will attempt to explain my issue as clearly as possible while also avoid making this topic too long. I recently found the Chart.js library, which is excellent for what I need. Now, since I am using Node.js and need a png of the graph, I am utilizing the chartjs-node-canvas library. Having this information in mind, I will try to split my topic into multiple sections for a clearer understanding.
Ultimate Goal
Before getting into the problem itself, I would like to discuss my ultimate goal. This is to give a general idea on what I'm trying to do so the responses are fitted accordingly. To keep this short, I have data in the form of {awardedDate: "2022-06-22T12:21:17.22Z", badgeId: 1234567}, with awardedDate being a timestamp of when the badge was awarded, and the badgeId being the ID of the badge that was awarded (which is irrelevant to the graph, but it exists because it's part of the data). Now, I have a sample with around 2,787 of these objects, with all having different award dates and IDs, and with dates ranging from 2016 to 2022. My objective is to group these badges by month-year, and that month-year will have the amount of badges earned for that month during that year. With that data, I then want to make a waterfall graph which is based on the amount of badges earned that month of that year. As of right now, there isn't a specific structure on how this will look like, but it could range from an object that looks like {"02-2022": 10, "03-2022": 5} to anything else. I can of course restructure this format based on what is required for a waterfall graph.
Actual Questions
Now that you have a general idea of what my ultimate goal is, my actual question is how I'd be able to make a floating (we can leave the waterfall structure stuff for another topic) bar graph with that data. Since the data can have blank periods (it is possible for a dataset to have gaps that are months long), I cannot really utilize labels (unless I am saying something wrong), so an x-y relation works the best. I tried using the structure of {x: "2022-06-22T12:21:17.226Z", y: [10, 15]}, but that didn't really yield any results. As of right now, I am using a sample code to test how the graph reacts with the data, and of course I'll replace the test values with actual values once I have a finished product. Here is my code so far:
const config = {
type: "bar",
data: {
datasets: [{
label: "Badges",
data: [
{
x: "2022-06-22T12:41:17.226Z",
y: [10, 15]
}
],
borderColor: "rgb(75, 192, 192)",
borderSkipped: false
}]
},
options: {
plugins: {
legend: {
display: false
},
title: {
display: true,
text: "Test",
color: "#FFFFFF"
}
},
scales: {
x: {
type: 'time',
title: {
display: true,
text: 'Time',
color: "#FFFFFF"
},
min: "2022-06-22T12:21:17.226Z",
max: "2022-06-22T14:21:17.226Z",
grid: {
borderColor: "#FFFFFF",
color: "#FFFFFF"
},
ticks: {
color: "#FFFFFF"
}
},
y: {
title: {
display: true,
text: 'Number of Badges',
borderColor: "#FFFFFF",
color: "#FFFFFF"
},
min: 0,
max: 50,
grid: {
borderColor: "#FFFFFF",
color: "#FFFFFF"
},
ticks: {
color: "#FFFFFF"
}
}
}
},
plugins: [
{
id: 'custom_canvas_background_color',
beforeDraw: (chart) => {
const ctx = chart.ctx;
ctx.save();
ctx.fillStyle = '#303030';
ctx.fillRect(0, 0, chart.width, chart.height);
ctx.restore();
}
}
]
};
const imageBuffer = await canvasRenderService.renderToBuffer(config)
fs.writeFileSync("./chart2.png", imageBuffer)
And this is the graph that the code produces:
What is supposed to happen, of course, is that a float bar should be generated near the start that ranges from 5 to 10, but as seen above, nothing happens. If someone could assist me in my problem, that would be amazing. Thank you very much for your time and help, I greatly appreciate it.
Inspired by this answer, I came up with the following solution.
const baseData = [
{ awardedDate: "2022-06-22T12:21:17.22Z" },
{ awardedDate: "2022-06-18T12:21:17.22Z" },
{ awardedDate: "2022-06-15T12:21:17.22Z" },
{ awardedDate: "2022-05-20T12:21:17.22Z" },
{ awardedDate: "2022-05-10T12:21:17.22Z" },
{ awardedDate: "2022-04-16T12:21:17.22Z" },
{ awardedDate: "2022-04-09T12:21:17.22Z" },
{ awardedDate: "2022-04-03T12:21:17.22Z" },
{ awardedDate: "2022-04-01T12:21:17.22Z" },
{ awardedDate: "2022-02-18T12:21:17.22Z" },
{ awardedDate: "2022-02-12T12:21:17.22Z" },
{ awardedDate: "2022-01-17T12:21:17.22Z" }
];
const badgesPerMonth = baseData
.map(o => o.awardedDate)
.sort()
.map(v => moment(v))
.map(m => m.format('MMM YYYY'))
.reduce((acc, month) => {
const badges = acc[month] || 0;
acc[month] = badges + 1;
return acc;
}, {});
const months = Object.keys(badgesPerMonth);
const labels = months.concat('Total');
const data = [];
let total = 0;
for (let i = 0; i < months.length; i++) {
const vStart = total;
total += badgesPerMonth[months[i]];
data.push([vStart, total]);
}
data.push(total);
const backgroundColors = data
.map((o, i) => 'rgba(255, 99, 132, ' + (i + (11 - data.length)) * 0.1 + ')');
new Chart('badges', {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Badges',
data: data,
backgroundColor: backgroundColors,
barPercentage: 1,
categoryPercentage: 0.95
}]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: ctx => {
const v = data[ctx.dataIndex];
return Array.isArray(v) ? v[1] - v[0] : v;
}
}
}
},
scales: {
y: {
ticks: {
beginAtZero: true,
stepSize: 2
}
}
}
}
});
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="badges" height="95"></canvas>
If you also want to see the gaps, you would first have to initialize badgesPerMonth with following months between the earliest and latest date, each with value zero. Please take a look at this answer to get an idea about how this could be done.
After reading #uminder's reply, I was able to create the following code which solved my problem:
dateGroups = Object.fromEntries(
Object.entries(dateGroups).sort(([d1,],[d2,]) => {return (d1 < d2) ? -1 : ((d1 > d2) ? 1 : 0)})
)
const dateTimesConst = Object.keys(dateGroups)
const dateValuesConst = Object.values(dateGroups)
let dateTimes = []
let dateValues = []
let prevLength = 0
let mostBadgesPerMonth = 0
for (let i = 0; i < dateValuesConst.length; i++) {
const currentMonth = new Date(Date.parse(dateTimesConst[i]))
const previousMonth = new Date(Date.UTC(currentMonth.getUTCFullYear(), currentMonth.getUTCMonth() - 1, 1, 0, 0, 0, 0)).toISOString()
const nextMonth = new Date(Date.UTC(currentMonth.getUTCFullYear(), currentMonth.getUTCMonth() + 1, 1, 0, 0, 0, 0)).toISOString()
// if (!dateTimesConst.includes(previousMonth)) prevLength = 0
const length = dateValuesConst[i].length
dateValues.push([prevLength, length])
dateTimes.push(dateTimesConst[i])
prevLength = length
if (length > mostBadgesPerMonth) mostBadgesPerMonth = length
// if (!dateTimesConst.includes(nextMonth) && i !== dateValuesConst.length - 1) {
// dateTimes.push(nextMonth)
// dateValues.push([length, 0])
// prevLength = 0
// }
}
function barColorCode() {
return (ctx) => {
const start = ctx.parsed._custom.start
const end = ctx.parsed._custom.end
return start <= end ? "rgba(50, 168, 82, 1)" : (start > end) ? "rgba(191, 27, 27, 1)" : "black"
}
}
const config = {
type: "bar",
data: {
labels: dateTimes,
datasets: [{
label: "Badges",
data: dateValues,
elements: {
bar: {
backgroundColor: barColorCode()
}
},
barPercentage: 1,
categoryPercentage: 0.95,
borderSkipped: false
}]
},
options: {
plugins: {
legend: {
display: false
},
title: {
display: true,
text: "Test",
color: "#FFFFFF"
}
},
scales: {
x: {
type: 'time',
title: {
display: true,
text: 'Date',
color: "#FFFFFF"
},
time: {
unit: "month",
round: "month"
},
min: dateTimesConst[0],
max: dateTimesConst[dateTimesConst.length - 1],
grid: {
borderColor: "#FFFFFF",
color: "#FFFFFF"
},
ticks: {
color: "#FFFFFF"
}
},
y: {
title: {
display: true,
text: 'Number of Badges',
borderColor: "#FFFFFF",
color: "#FFFFFF"
},
min: 0,
max: mostBadgesPerMonth + 1,
grid: {
borderColor: "#FFFFFF",
color: "#FFFFFF"
},
ticks: {
color: "#FFFFFF"
}
}
}
},
plugins: [
{
id: 'custom_canvas_background_color',
beforeDraw: (chart) => {
const ctx = chart.ctx;
ctx.save();
ctx.fillStyle = '#303030';
ctx.fillRect(0, 0, chart.width, chart.height);
ctx.restore();
}
}
]
};
const imageBuffer = await canvasRenderService.renderToBuffer(config)
fs.writeFileSync("./chart2.png", imageBuffer)
Again, big thanks to #uminder for the inspiration.
I have a Vaadin14-based project with Polymer3 components.
I created a small wrapper for Highcharts HighStock component without using embedded Vaadin Charts.
Now I need to add a stock-tools panel to allow drawing on chart.
All needed .js and .css seemed to be added according to manuals as chart is displayed correctly along with stock-tools panel.
I can see sub-menus, change tools etc.
But I unable to draw anything on chart.
Seems like tool-button click does not turn the chart in drawing mode (style for active button or highcharts-draw-mode are not applied).
Highcharts version doesn't matter as far as I tried to update from 8 to 10 via npm.
Does anybody know the reason why stock-tool events don't work?
Thanks in advance.
The Polymer component code with some cuts is following:
import { html } from '#polymer/polymer/lib/utils/html-tag.js';
import Highcharts from 'highcharts/es-modules/masters/highstock.src.js';
import 'highcharts/es-modules/masters/modules/hollowcandlestick.src.js';
import 'highcharts/es-modules/masters/modules/data.src.js';
import 'highcharts/es-modules/masters/modules/debugger.src.js';
import 'highcharts/es-modules/masters/modules/accessibility.src.js';
import 'highcharts/es-modules/masters/modules/boost.src.js';
import 'highcharts/es-modules/masters/indicators/indicators-all.src.js';
import 'highcharts/es-modules/masters/modules/drag-panes.src.js';
import 'highcharts/es-modules/masters/modules/price-indicator.src.js';
import 'highcharts/es-modules/masters/modules/full-screen.src.js';
import 'highcharts/es-modules/masters/modules/annotations-advanced.src.js';
import 'highcharts/es-modules/masters/modules/stock-tools.src.js';
import 'highcharts/es-modules/masters/modules/heikinashi.src.js';
class StockChartComponent extends PolymerElement {
static get template() {
return html`
<style include="shared-styles shared-chart-styles">
:host {
border: 1px solid red;
width: 100%;
height: 100%;
display: block;
padding: 1em;
}
#container { border: 1px solid blue; }
</style>
<div class='chart stock-chart' id='container'> </div>
`;
}
static get is() {
return 'stock-chart-component';
}
connectedCallback() {
super.connectedCallback();
}
/**this method is called after some initialization on the server-side via executeJS(...) **/
onStockChartUpdate(options) {
var container = this.shadowRoot.querySelector("#container");
if (Highcharts && options && container) {
Highcharts.getJSON('https://demo-live-data.highcharts.com/aapl-ohlcv.json', function (data) {
// split the data set into ohlc and volume
var ohlc = [],
volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i += 1) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
volume.push([
data[i][0], // the date
data[i][5] // the volume
]);
}
Highcharts.stockChart(container, {
yAxis: [{
labels: {
align: 'left'
},
height: '80%',
resize: {
enabled: true
}
}, {
labels: {
align: 'left'
},
top: '80%',
height: '20%',
offset: 0
}],
tooltip: {
shape: 'square',
headerShape: 'callout',
borderWidth: 0,
shadow: false,
positioner: function (width, height, point) {
var chart = this.chart,
position;
if (point.isHeader) {
position = {
x: Math.max(
// Left side limit
chart.plotLeft,
Math.min(
point.plotX + chart.plotLeft - width / 2,
// Right side limit
chart.chartWidth - width - chart.marginRight
)
),
y: point.plotY
};
} else {
position = {
x: point.series.chart.plotLeft,
y: point.series.yAxis.top - chart.plotTop
};
}
return position;
}
},
series: [{
type: 'ohlc',
id: 'aapl-ohlc',
name: 'AAPL Stock Price',
data: ohlc
}, {
type: 'column',
id: 'aapl-volume',
name: 'AAPL Volume',
data: volume,
yAxis: 1
}],
responsive: {
rules: [{
condition: {
maxWidth: 800
},
chartOptions: {
rangeSelector: {
inputEnabled: false
}
}
}]
}
});
});
}
}
}
customElements.define(StockChartComponent.is, StockChartComponent);
I'm trying to use ZingChart. Trying to build gauge widget. Question is for those who worked with zingChart. How to configure width and height of space around chart. So here is what i'm saying about:
White container is a div with 100% width and height. All yellow space is plotarea of the zingChart, and in the center is gauge.
I want to cut all yellow space at the top and bottom around gauge. How to configure that?
Here is my chart config in react:
import React from 'react'
import './PlanGauge.sass'
import 'zingchart/es6'
import ZingChart from 'zingchart-react'
import WidgetTile from '../WidgetTile/WidgetTile'
function PlanGauge({ title }) {
const widgetConfig = {
minValue: 0,
maxValue: 150000,
currentValue: 100000,
}
const chartConfig = {
type: 'gauge',
'scale-r': {
aperture: 180,
values: `${widgetConfig.minValue}:${widgetConfig.maxValue}`,
ring: {
size: 12,
'background-color': '#F2F4F6',
tick: {
visible: false,
},
},
center: {
visible: false,
},
tick: {
visible: false,
},
item: {
//Scale Label Styling
visible: false,
},
},
plot: {
size: '100%',
},
series: [
{
values: [widgetConfig.currentValue],
'background-color': '#000',
'border-color': 'red',
indicator: [4, 4, 0, 0, 0.9],
},
],
plotarea: {
marginTop: 0,
marginBottom: 0,
backgroundColor: 'yellow',
},
}
return (
<WidgetTile title={title}>
<ZingChart data={chartConfig} />
</WidgetTile>
)
}
export default PlanGauge
Please set padding in the ZingChart configuration's plot object to control the area around it. The Plot object controllers the styling of the chart.
Set margin in the ZingChart configuration.
plotarea: {
margin: '0 0 0 0',
},
It works for me.
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>
);
}