Vue Chart.js - simple dot/line on bar chart - vue.js

I'd need to add a simple dot/vertical line on my bar chart that has a dynamical X value, and 0 for Y value. Preview of what I need (the red dot):
Where the green values are dynamic.
Preview of my current state:
Where 3.30 should be the X coordinate of the dot - [3.30, 0].
I'm using Vue chart for the charts and I tried do create a mixed one with the bar and scatter but scatter requires type: 'linear' for it's xAxis which doesn't suit my need for the bar chart.
So I tried with chartjs-plugin-annotation and it's box type which accepts "coordinates" but the problem here is that the X value must be a fixed value on the X axis (labels object). If I put for the X axis [3,0] it will work, but if there is a decimal number, like [3.5, 0], it won't work.
// data
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 1,
stepSize: 0.1
}
}]
}
}
// computed
labels: [1, 2, 3, 4, 5, 6], // fixed value, there are always 6 bars
datasets: [
{
label: 'Values',
backgroundColor: '#f89098',
data: this.tableInputValues // array of decimal values
}
]
So, my question is how to put a "simple" dot, or a vertical line, on a Chart.js bar chart where the dot has a dynamical value for the X axis -> [dynamic value, 0].
FYI - it's about Expected value

As far as I understand Vue Chart works using canvas (as seen on Demo page).
So, my suggestion here is to retrieve the canvas node representing the chart in your DOM and dynamically write the desired dot. For example:
var c = document.getElementById("bar-chart"); //hereby assuming canvas named "bar-chart"
var ctx = c.getContext("2d");
ctx.fillStyle = "#ff0000"; //red color for the dot
ctx.beginPath();
let yPosition = c.height - 5; //fixed y position
let xPosition = 35; //that's the dynamic expected value
ctx.arc(xPosition, yPosition, 2.5, 0, 2 * Math.PI);
ctx.fill();
Here you find a demo showing how to achieve that using Vue. In this scenario, you need to wrap the code to draw a dot on the canvas in a afterDraw hook. This hook needs to be attached to the chart component as a plugin, so like this:
...
mounted () {
//adding the plugin to draw the red dot
this.addPlugin({
id: 'chart-plugin',
afterDraw: function (chart) {
var c = chart.canvas;
var ctx = c.getContext("2d");
ctx.fillStyle = "#ff0000";
ctx.beginPath();
let xPosition = 742; //x positioning to be calculated according to your needs
let yPosition = c.height - 28;
ctx.arc(xPosition, yPosition, 3, 0, 2 * Math.PI);
ctx.fill();
}
});
//actual chart rendering
this.renderChart({
...
});
}
...
For the sake of completeness, here you find the list of all the available hooks of Chart.js plugin API.

This is my solution for your problem https://jsfiddle.net/huynhsamha/e54djwxp/
And this is screenshot for the result
In my solution, I use type="line" and both x-axis and y-axis with type="linear". I also add property options to <chart> for using options in ChartJS
<div id="vue">
<chart type="line" :data="data" :options="options"></chart>
</div>
The options will set-up x-axis and y-axis to render the data points and expected value:
options: {
scales: {
xAxes: [{
type: 'linear',
ticks: {
min: 1,
max: 6,
stepSize: 1
}
}],
yAxes: [{
type: 'linear',
ticks: {
min: 0,
max: 1,
stepSize: 0.1
}
}]
}
}
And the data will have 2 datasets. The first is data points, use type line, and the second is the expected value which use type bubble.
data: {
datasets: [{
label: 'Frequency Data',
data: dataPoints.map(({ val, freq }) => ({
x: val,
y: freq
})),
backgroundColor: 'rgba(72, 202, 59, 0.4)',
borderColor: 'rgba(72, 202, 59, 1)'
}, {
label: 'Expected Value',
type: 'bubble',
data: [{
x: expectedValue,
y: 0,
r: 8 // radius
}],
backgroundColor: 'rgba(255, 68, 0, 0.4)',
borderColor: 'rgba(255, 68, 0, 1)'
}]
},
In datasets, we have dataPoints and expectedValue, it will be fetched from API to get your data points. I also simulate the simple API for data points:
// simulate the API to get data points
const retrieveData = () => [
{ val: 1, freq: 0.15 },
{ val: 2, freq: 0.25 },
{ val: 3, freq: 0.3 },
{ val: 4, freq: 0.2 },
{ val: 5, freq: 0.1 },
{ val: 6, freq: 0.45 }
]
// fetch your data here, return array of JSON { val, freg }
const dataPoints = retrieveData() || [];
// calculate expected value = sum( val * freq ) each i in dataPoints
const expectedValue = dataPoints.reduce((cur, { val, freq }) => cur + val * freq, 0).toFixed(4);
You can run snippet or run on fiddle https://jsfiddle.net/huynhsamha/e54djwxp/92/
<script async src="//jsfiddle.net/huynhsamha/e54djwxp/92/embed/js,html,css,result/dark/"></script>

Related

chartjs different grid using mixed chart types

I am currently trying to use mixed chart types with vue-chartjs for a bar chart and a line chart(vue-chartjs#4.1.2, vuejs#2.6.14, chartjs#3.0.0).
As you can see in the following image the grid for the line chart (colored red) is not aligned with the grid for the bar chart.
mixed chart types
How I'm implementing the mixed chart types
const
chartContainer = this.chartContainer = this.chartContainer || document.createElement('canvas'),
data = {
datasets : [
{
data : rcd.getLineData(tAx.records),
borderColor : '#ff9e9e',
hoverBackgroundColor : '#ff0000',
fill : false,
stepped : 'end',
type : 'line',
xAxisID: 'xLine',
radius: 0,
},
{
data : rcd.getBarData(tAx.records, record, tAxs),
borderColor : '#ff9e9e',
backgroundColor : 'rgba(187,242,193,1)',
hoverBackgroundColor : '#a5eeac',
fill : true,
stepped : true,
type : 'bar',
barPercentage : 1.0,
categoryPercentage: 1.0,
xAxisID: 'xBar'
}
};
chartContainer.setAttribute('height', 100);
chartContainer.setAttribute('width', tAxModel.totalSize);
this.element.appendChild(chartContainer);
this.chart = new Chart(
chartContainer,
{
drawBorder : false,
data,
options : {
responsive : false,
animation : {
duration : 0
},
elements : {
point : {
radius : 0,
hoverRadius : 0
}
},
layout : {
padding : {
top : 5,
left : -10,
bottom : -19
}
},
plugins : {
legend : {
display : false
}
},
scales : {
xLine : {
offset: false,
grid : {
display : true,
offset : true,
color: 'red'
},
ticks : {
display : false,
}
},
xBar : {
grid : {
display : true,
offset : true
},
ticks : {
display : false,
}
},
y : {
borderWidth : 0,
min : 0,
ticks : {
display : false,
borderWidth : 0,
},
grid : {
borderWidth : 0,
display : true
}
},
},
tooltips: {
mode: 'index'
},
interaction : {
mode: 'index',
intersect : false,
axis : 'x'
}
},
}
);
Both charts get arrays with the same length and the same x-values for each item.
For example bar and line chart receive an array with values like {x: 'February 13, 2023', y: (value for bar or line chart)}
Logging this.chart and this.chart._sortedMetaSets I kind of found out that the difference for one pointElement to the next pointElement for line charts data is not equal to bar charts data.
For instance line charts pointElements: {x: 0, ...}, {x: 71.25, ...} -> it's 71.25 - but for bar charts pointElements: {x: 35, ...}, {x: 105, ...} -> it's 70.
Furthermore I found that the categoryScale for bar chart has difference to the line charts categoryScale.
Examples are _gridLineItems, _valueRange and _startValue.
Is there anything wrong in my implementation or my data?
Thank you in advance!

threeJS Raycaster.set() not detecting intersections ( plane )

const origin = new THREE.Vector3(...point, -100),
direction = new THREE.Vector3(0, 0, 1) // is a normalized vector
const raycaster = new THREE.Raycaster( origin, direction );
const intersects = raycaster.intersectObject( dem ); // is a planeGeometry (mesh)
const length = 2000;
const hex = 0xff0000;
const arrowHelper = new THREE.ArrowHelper( direction, origin, length, hex );
cx3d.addObject( arrowHelper );
if( intersects.length ){
console.log( intersects[0] )
}
now intersects = [], but point is in the plane mesh, so I need help, thank everyone
like this https://jsfiddle.net/Hoshua/obm8ke0q/2/
You need to update your mesh matrix world with mesh.updateMatrixWorld();. See below.
function seta(){
const origin = new THREE.Vector3(0.5, 0, 0),
direction = new THREE.Vector3(-1, 0, 0)
const raycaster = new THREE.Raycaster( origin, direction );
mesh.updateMatrixWorld(); // here
const intersects = raycaster.intersectObject( mesh );
const length = 1.5;
const hex = 0xff0000;
const arrowHelper = new THREE.ArrowHelper( direction, origin, length, hex );
scene.add( arrowHelper );
console.log(intersects)
}
Not sure if link will work. In case: https://jsfiddle.net/4n0tgwuo/
Output:
[{
distance: 0.5,
face: {
a: 0,
b: 2,
c: 1,
materialIndex: 0,
normal: { ... }
},
faceIndex: 0,
object: {
animations: [],
castShadow: false,
children: [],
frustumCulled: true,
geometry: { ... },
isMesh: true,
isObject3D: true,
layers: { ... },
material: { ... },
matrix: { ... },
matrixAutoUpdate: true,
matrixWorld: { ... },
matrixWorldNeedsUpdate: false,
name: "",
parent: { ... },
position: { ... },
quaternion: { ... },
receiveShadow: false,
renderOrder: 0,
rotation: { ... },
scale: { ... },
type: "Mesh",
up: { ... },
userData: { ... },
uuid: "cb14eb31-b325-4252-8fb6-0d4417cbf39d",
visible: true
},
point: {
isVector3: true,
x: 0,
y: 0,
z: 0
},
uv: {
isVector2: true,
x: 0.5,
y: 0.5
}
}, {
distance: 0.5,
face: {
a: 2,
b: 3,
c: 1,
materialIndex: 0,
normal: { ... }
},
faceIndex: 1,
object: [circular object Object],
point: {
isVector3: true,
x: 0,
y: 0,
z: 0
},
uv: {
isVector2: true,
x: 0.5,
y: 0.5
}
}]

Chartist Pie Char Custom Label

I am trying to customize the label of Chartist Pie Chart so that it will show both the label and value.
So in the example below, I would want the label to show "Bananas - 20", "Apples - 15", "Grapes - 40". I know I can just change the labels:, but is there a way to do that with the labelInterpolationFnc?
https://jsfiddle.net/ckmz7L1p/
var data = {
labels: ['Bananas', 'Apples', 'Grapes'],
series: [20, 15, 40]
};
var options = {
labelInterpolationFnc: function(value) {
return value[0]
}
};
var responsiveOptions = [
['screen and (min-width: 640px)', {
chartPadding: 30,
labelOffset: 100,
labelDirection: 'explode',
labelInterpolationFnc: function(value) {
return value;
}
}],
['screen and (min-width: 1024px)', {
labelOffset: 80,
chartPadding: 20
}]
];
new Chartist.Pie('.ct-chart', data, options, responsiveOptions);
Got it figured out. Didn't realize labelInterpolationFnc can take function with both value and index parameters.
var data = {
labels: ['Bananas', 'Apples', 'Grapes'],
series: [20, 15, 40]
};
var options = {
width: "400px",
height: "400px",
labelInterpolationFnc: function(value, idx) {
return value + " - " + data.series[idx];
}
};
var responsiveOptions = [
['screen and (min-width: 640px)', {
chartPadding: 0,
labelOffset: 0,
labelDirection: 'explode',
labelInterpolationFnc: function(value, idx) {
return value + " - " + data.series[idx];
}
}],
['screen and (min-width: 1024px)', {
labelOffset: 30,
chartPadding: 0
}]
];
new Chartist.Pie('.ct-chart', data, options, responsiveOptions);

renderer in series block in the chart extjs4

I would like to change color of chart in extjs type ='pie'.
Can I use renderer in the series block please see the example:
..... },
series : [ {
type : 'bar',
axis : 'bottom',
gutter : 0,
groupGutter : 0,
yField : this.fields,
title : this.fieldTitles,
stacked : true,
fill: true,
scope: this,
renderer: function(sprite, record, attr, index, store) {
var color = this.fieldColors[index];
return Ext.apply(attr, {
fill: color
});
},.....
Instead of a custom renderer, you can use the colorSet property for your series.
series: [{
colorSet: this.fieldColors,
...
}]
See http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.chart.series.Pie-cfg-colorSet

Ext.dataview.ListView : Disable Overscroll?

In the sencha scrollable views, like Ext.dataview.ListView, we can always scroll the list of elements out of the screen.
If I take this example : http://dev.sencha.com/deploy/touch/examples/production/kitchensink/#demo/list
Is there a way to block the list item "Alana Wiersma" ? I want this item to be with "top <= 0px".
Your problem is exactly called overscrolling. Try this:
scrollable : {
direction: 'horizontal',
directionLock: true,
momentumEasing: {
momentum: {
acceleration: 30,
friction: 0.5
},
bounce: {
acceleration: 0.0001,
springTension: 0.9999,
},
minVelocity: 5
},
outOfBoundRestrictFactor: 0
}
My first guess would be to set up the scroller of the list with an initial offset
config:{
scrollable:{
direction:'vertical',
initialOffset : {x: 0, y: VALUE}
}
}
And replace VALUE with whatever value you need
Hope this helps