How put label into bar with vue-charjs - vuejs2

Hi I need help with put value into bar with simbole % how de image
I try with install chartjs-plugin-datalabels but dont work.
The value I need is the value I get with which the bar is measured
The version is :
"chart.js": "^2.7.3",
"vue-chartjs": "^3.4.0",
I can't change the version becouse I have others graphics in these versions
My code
const horizonalLinePlugin = {
id: 'horizontalLine',
afterDraw: function (chartInstance) {
var yValue;
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index;
var line;
var style;
var fontSize = (200 / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
var data = ['20%', '30%', '40%', '60%', '10%', '30%', '20%'];
// var dataPresupuesto = ['10', '20', '30', '40', '10', '30', '20'];
var positionX = 130;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
if (!line.style) {
style = "#080808";
} else {
style = line.style;
}
if (line.y) {
yValue = yScale.getPixelForValue(line.y);
} else {
yValue = 0;
}
ctx.lineWidth = 3;
if (yValue) {
window.chart = chartInstance;
ctx.beginPath();
ctx.moveTo(0, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
}
}
}
import { Bar } from 'vue-chartjs'
// import ChartJSPluginDatalabels from "chartjs-plugin-datalabels";
export default {
beforeMount() {
this.addPlugin(horizonalLinePlugin)
},
extends: Bar,
mounted() {
// Overwriting base render method with actual data.
this.renderChart({
labels: ['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07'],
datasets: [
{
label: 'Producción',
backgroundColor: '#000349',
data: [40, 39, 10, 40, 39, 80, 40]
},
{
label: 'Presupuesto',
backgroundColor: '#3AA9E0',
data: [40, 39, 10, 40, 39, 80, 40]
}
]
},
{
scales: {
xAxes: [{
stacked: true,
categoryPercentage: 0.5,
barPercentage: 1,
scaleLabel: {
display: true,
labelString: 'Semanas Comerciales'
}
}],
yAxes: [{
stacked: true,
}]
},
responsive: false,
plugins: {
datalabels: {
display: true,
color: "white",
textAlign: "center",
font: {
weight: "bold",
size: 16
}
}
}
})
}
}
Please someone that cant help me

Related

get selected value from first chart into dynamic second chart | Apexchart dynamic charts

the issue im facing is when i end 2nd chart like 'chart.render()' , 2nd chart gets value that i selected in first chart but when i click on another value in first chart , instead of update 2nd chart div , it creats another div vertically.
here is my chart.
i'm getting value from controlle in chart.
var app = #json($newval);
var options = {
series: app,
chart: {
events: {dataPointSelection:function (event, chartContext, config) {
var value= config.w.config.series[config.dataPointIndex]
$( "#chart2" ).load(window.location.href + " #chart2" );
secondchart(value);
}
},
width: 380,
type: 'donut',
},
dataLabels: {
enabled: false
},
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
show: false
}
}
}],
legend: {
position: 'right',
offsetY: 0,
height: 230,
}
};
var chart = new ApexCharts(document.querySelector("#chart1"), options);
chart.render();
//second chart starts...
function secondchart(value) {
//in this console.log im getting correct value
console.log(value)
var options = {
series: [{
data: [value]
}],
chart: {
type: 'bar',
height: 350
},
plotOptions: {
bar: {
borderRadius: 4,
horizontal: true,
}
},
dataLabels: {
enabled: false
},
xaxis: {
categories: ['South Korea', 'Canada', 'United Kingdom', 'Netherlands', 'Italy', 'France', 'Japan',
'United States', 'China', 'Germany'
],
}
};
chart.render()
}
</script>```
so here is code what i want do do exactly,
<script>
var app = #json($newval);
var options = {
series: app,
chart: {
events: {
dataPointSelection: function (event, chartContext, config) {
var value = config.w.config.series[config.dataPointIndex]
secondchart(value);
}
},
width: 380,
type: 'donut',
},
dataLabels: {
enabled: false
},
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
show: false
}
}
}],
legend: {
position: 'right',
offsetY: 0,
height: 230,
}
};
var chart = new ApexCharts(document.querySelector("#chart1"), options);
chart.render();
function secondchart(value) {
var cat = #json($cat);
var options = {
series: [{
data: [value,value]
}],
chart: {
redrawOnParentResize: true,
type: 'bar',
height: 350
},
plotOptions: {
bar: {
borderRadius: 4,
horizontal: true,
}
},
dataLabels: {
enabled: false
},
xaxis: {
categories: [cat
],
}
};
// $( "#chart2" ).load(window.location.href + " #chart2" );
var chart = new ApexCharts(document.querySelector("#chart2"), options);
debugger
if ($("#chart2") == null) {
console.log( $("#chart2"));
chart.render()
} else {
$("#chart2").empty();
console.log( $("#chart2"));
chart.render()
}
}
</script>

Vue-Charts label numbers to the side of a bar chart

I am using a Nuxt application with vue-charts. I have a barchart that I trying to see if there is a way to callback the numbers next to the chart. Some what like this
My barchart options look like this now.
barLostDollarChartOptions: {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false,
},
title: {
display: true,
text: 'Daily NP Opportunity Costs'
},
scales: {
yAxes: [{
//Sets the Max value after re-rendering chart
beforeFit: function (scale){
let maxValue = 0
if (scale.chart.config && scale.chart.config.data && scale.chart.config.data.datasets) {
scale.chart.config.data.datasets.forEach(dataset => {
if (dataset && dataset.data) {
dataset.data.forEach(value => {
if (value > maxValue) {
maxValue = value
}
})
}
})
}
// After, set max option !!!
scale.options.ticks.max = maxValue
},
// afterFit: function (scale){
// console.log('yAxes',scale)
// let arr = Object.values(scale.chart.config.data.datasets[0].data);
// let min = Math.min(...arr);
// let max = Math.max(...arr);
// maxValueArray.push(max)
// // console.log( `Min value: ${min}, max value: ${max}` );
//
// }
}
],
xAxes: [{
ticks:{
callback: function(value, index, values) {
if(parseInt(value) >= 1000){
// console.log(value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","))
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
},
},
}]
}
},
But I am trying to see if there is a way that I can call back the number and render it next to the bar? any ideas?
You can use the datalabels plugin for this:
Chart.plugins.register(ChartDataLabels);
var options = {
type: 'horizontalBar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'orange'
}]
},
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
formatter: (val) => ('$' + val)
}
}
}
}
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/2.9.4/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/1.0.0/chartjs-plugin-datalabels.js"></script>
</body>

Can't trigger beforeDraw with Vue-Chartjs (or any other plugins)

I'm trying to add custom text to the Chartjs chart (using vue-chartjs), what I've found out so far is that I need to do this via beforeDraw (or similar) plugin. I included the plugin in the options.plugins, but it doesn't get triggered.
What am I doing wrong? Here's the code
<script>
import {Scatter} from "vue-chartjs";
export default {
extends: Scatter,
props: {
chartdata: {
type: Object,
default: null
},
options: {
type: Object,
default: null
}
},
mounted () {
this.renderChart(this.chartdata, {
scales: {
xAxes: [{
ticks: {
max: 100,
min: -100
},
type: 'linear',
}],
yAxes: [{
display: true,
type: 'linear',
ticks: {
max: 100,
min: -100
}
}]
},
elements: {
point: {
pointStyle: 'circle',
radius: 16,
backgroundColor: "#dc005a"
}
},
layout: {
padding: {
left: 25,
right: 25,
top: 25,
bottom: 25
}
},
plugins: [{
id: "AddLegend",
beforeDraw(chart) {
console.log(chart)
},
}],
});
}
}
</script>
Plugins can optionally be registered globally through Chart.plugins.register. You can register any of the hooks provided by the Plugin Core API and provide your custom code. The afterDraw hook for example would have to be registered as follows:
Chart.plugins.register({
afterDraw: chart => {
// your code
}
});
mounted () {
this.addPlugin({
id: 'my-plugin',
afterDraw: function (chart) {
var ctx = chart.ctx;
ctx.font = "bold 20px FiraGO";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("ლიბერალური", chart.width/2, chart.height - 25);
ctx.font = "bold 20px FiraGO";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("ავტორიტარული", chart.width/2, 25);
ctx.font = "bold 20px FiraGO";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.rotate(Math.PI/2);
ctx.fillText("გეგმიური ეკონომიკა", chart.width/(-2), 25);
// ctx.save();
ctx.fillText("თავისუფალი ეკონომიკა", chart.width/(-2), chart.height - 25);
// ctx.save();
// ctx.rotate(Math.PI/(-2))
// ctx.save();
}
});
this.renderChart(this.chartdata, {
scales: {
xAxes: [{
ticks: {
max: 100,
min: -100
},
type: 'linear',
}],
yAxes: [{
display: true,
type: 'linear',
ticks: {
max: 100,
min: -100
}
}]
},
elements: {
point: {
pointStyle: 'circle',
radius: 16,
backgroundColor: "#dc005a"
}
},
layout: {
padding: {
left: 50,
right: 50,
top: 50,
bottom: 50
}
},
});
}

how can I show the data label on the dot of the graph? ng2chart

https://valor-software.com/ng2-charts/#/LineChart
That is the link I followed for the line chart. I was able to show the data on the pie graph but it seems like different on this line chart. Like the graph below, how can I show data on the graph?
Update
I added a long line of code below. Typescript file can be also found in the the link above.
html
<div class="flex">
<div class="flex-item">
<div style="display: block;">
<canvas
baseChart
height="30vh"
width="70vw"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[options]="lineChartOptions"
[colors]="lineChartColors"
[legend]="lineChartLegend"
[chartType]="lineChartType"
[plugins]="lineChartPlugins"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"
></canvas>
</div>
</div>
</div>
ts
import { Component, OnInit, ViewChild } from "#angular/core";
import { BaseChartDirective, Color, Label } from "ng2-charts";
import { ChartDataSets, ChartOptions } from "chart.js";
import * as pluginAnnotations from "chartjs-plugin-annotation";
#Component({
selector: "kt-chart1",
templateUrl: "./chart1.component.html",
styleUrls: ["./chart1.component.scss"],
})
export class Chart1Component implements OnInit {
public lineChartData: ChartDataSets[] = [
{
data: [180, 33, 200, 300, 333, 270, 200],
label: "Cost",
yAxisID: "y-axis-1",
},
];
public lineChartLabels: Label[] = [
"01/05/2020",
"02/05/2020",
"03/05/2020",
"04/05/2020",
"05/05/2020",
"06/05/2020",
"07/05/2020",
];
public lineChartOptions: ChartOptions & { annotation: any } = {
plugins: {
labels: {
fontColor: ["green", "white", "red"],
precision: 2,
textShadow: true,
render: function (args) {
return args.value + "(" + args.toFixed(1) + "%)";
},
position: "inside",
},
datalabels: {
formatter: () => {
return null;
},
},
},
responsive: true,
scales: {
// We use this empty structure as a placeholder for dynamic theming.
xAxes: [{}],
yAxes: [
{
id: "y-axis-1",
position: "right",
gridLines: {
color: "rgba(255,0,0,0.3)",
},
ticks: {
fontColor: "red",
},
},
],
},
annotation: {
annotations: [
{
type: "line",
mode: "horizontal",
scaleID: "y-axis-1",
value: "200",
borderColor: "red",
borderWidth: 2,
label: {
enabled: true,
fontColor: "orange",
content: "200",
},
},
],
},
tooltips: {
callbacks: {
label: (item, data) => {
console.log(item);
return "Cost: " + item.xLabel + " " + item.yLabel;
},
},
},
};
public lineChartColors: Color[] = [
{
// grey
backgroundColor: "rgba(148,159,177,0.2)",
borderColor: "rgba(148,159,177,1)",
pointBackgroundColor: "rgba(148,159,177,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(148,159,177,0.8)",
},
{
// dark grey
backgroundColor: "rgba(77,83,96,0.2)",
borderColor: "rgba(77,83,96,1)",
pointBackgroundColor: "rgba(77,83,96,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(77,83,96,1)",
},
{
// red
backgroundColor: "rgba(255,0,0,0.3)",
borderColor: "red",
pointBackgroundColor: "rgba(148,159,177,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(148,159,177,0.8)",
},
];
public lineChartLegend = true;
public lineChartType = "line";
public lineChartPlugins = [pluginAnnotations];
#ViewChild(BaseChartDirective, { static: true }) chart: BaseChartDirective;
constructor() {}
ngOnInit() {
}
public randomize(): void {
for (let i = 0; i < this.lineChartData.length; i++) {
for (let j = 0; j < this.lineChartData[i].data.length; j++) {
this.lineChartData[i].data[j] = this.generateNumber(i);
}
}
this.chart.update();
}
private generateNumber(i: number) {
return Math.floor(Math.random() * (i < 2 ? 100 : 1000) + 1);
}
// events
public chartClicked({
event,
active,
}: {
event: MouseEvent;
active: {}[];
}): void {
console.log(event, active);
}
public chartHovered({
event,
active,
}: {
event: MouseEvent;
active: {}[];
}): void {
console.log(event, active);
}
public hideOne() {
const isHidden = this.chart.isDatasetHidden(1);
this.chart.hideDataset(1, !isHidden);
}
public pushOne() {
this.lineChartData.forEach((x, i) => {
const num = this.generateNumber(i);
const data: number[] = x.data as number[];
data.push(num);
});
this.lineChartLabels.push(`Label ${this.lineChartLabels.length}`);
}
public changeColor() {
this.lineChartColors[2].borderColor = "green";
this.lineChartColors[2].backgroundColor = `rgba(0, 255, 0, 0.3)`;
}
public changeLabel() {
this.lineChartLabels[2] = ["1st Line", "2nd Line"];
// this.chart.update();
}
}
Instead of using chartjs-plugin-annotation, you can draw the labels directly on the canvas using the Plugin Core API. It offers a number of hooks that can be used to perform custom code. In your case, you could use the afterDraw hook and register it in the ngOnInit method as follows:
ngOnInit(): void {
Chart.pluginService.register({
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0']; // would be 'y-axis-1' in your code sample
ctx.save();
chart.data.labels.forEach((l, i) => {
var value = chart.data.datasets[0].data[i];
var x = xAxis.getPixelForValue(l);
var y = yAxis.getPixelForValue(value);
ctx.textAlign = 'center';
ctx.font = '12px Arial';
ctx.fillStyle = 'red';
ctx.fillText(value, x, y - 15);
});
ctx.restore();
}
});
}
Please have a look at this StackBlitz to see how it works.

how to keep the highligh on a bar chart?

var colors = ['url(#v-1)',
'url(#v-2)',
'url(#v-3)',
'url(#v-4)',
'url(#v-5)'];
var baseColor = '#eee';
Ext.define('Ext.chart.theme.Fancy', {
extend: 'Ext.chart.theme.Base',
constructor: function(config) {
this.callParent([Ext.apply({
axis: {
fill: baseColor,
stroke: baseColor
},
axisLabelLeft: {
fill: baseColor
},
axisLabelBottom: {
fill: baseColor
},
axisTitleLeft: {
fill: baseColor
},
axisTitleBottom: {
fill: baseColor
},
colors: colors
}, config)]);
}
});
var win = Ext.create('Ext.Panel', {
width: 1000,
height: 300,
hidden: false,
maximizable: true,
title: 'Column Chart',
renderTo: Ext.getBody(),
enableToggle: true,
pressed: true,
layout: 'fit',
items: {
id: 'chartCmp',
xtype: 'chart',
theme: 'Fancy',
animate: {
easing: 'bounceOut',
duration: 750
},
store: store,
background: {
fill: 'rgb(17, 17, 17)'
},
gradients: [
{
'id': 'v-1',
'angle': 0,
stops: {
0: {
color: 'rgb(212, 40, 40)'
},
100: {
color: 'rgb(117, 14, 14)'
}
}
},
{
'id': 'v-2',
'angle': 0,
stops: {
0: {
color: 'rgb(180, 216, 42)'
},
100: {
color: 'rgb(94, 114, 13)'
}
}
},
{
'id': 'v-3',
'angle': 0,
stops: {
0: {
color: 'rgb(43, 221, 115)'
},
100: {
color: 'rgb(14, 117, 56)'
}
}
},
{
'id': 'v-4',
'angle': 0,
stops: {
0: {
color: 'rgb(45, 117, 226)'
},
100: {
color: 'rgb(14, 56, 117)'
}
}
},
{
'id': 'v-5',
'angle': 0,
stops: {
0: {
color: 'rgb(187, 45, 222)'
},
100: {
color: 'rgb(85, 10, 103)'
}
}
}],
axes: [{
type: 'Numeric',
position: 'left',
fields: ['Quantidade'],
minimum: 0,
// maximum: 100,
label: {
renderer: Ext.util.Format.numberRenderer('0,0')
},
title: 'Numero de Processos',
grid: {
odd: {
stroke: '#555'
},
even: {
stroke: '#555'
}
}
}, {
type: 'Category',
position: 'bottom',
fields: 'Range',
title: 'Espaço temporal'
}],
series: [{
type: 'column',
axis: 'left',
highlight: true,
highlightCfg: {
fill: '#a2b5ca'
},
label: {
display: 'insideEnd',
'text-anchor': 'middle',
//Numero que aparece em cima da barra
field: 'Quantidade',
orientation: 'horizontal',
fill: '#fff',
font: '17px Arial'
},
renderer: function(sprite, storeItem, barAttr, i, store) {
barAttr.fill = colors[i % colors.length];
return barAttr;
},
style: {
opacity: 0.95
},
listeners: {
'itemmousedown': function(item) {
if(!flag) return flag;
flag = false;
var cmp = Ext.getCmp('chartCmp');
var series = cmp.series.get(0);
index = Ext.Array.indexOf(series.items, item);
selectionModel = grid.getSelectionModel();
selectedStoreItem = item.storeItem;
var as = selectedStoreItem.data.Range;
storeDadosFiltrados.proxy.extraParams.range = as;
storeDadosFiltrados.load();
}
},
xField: 'Range',
yField: ['Quantidade']
}]
},
renderTo:'grafico'
});
});
image of the chart--> http://alojaimagens.com/viewer.php?file=zz7slhsprnopuoui1mpv.jpg
I am selecting the first column, and i don't click it, just with the mouse over it. The higlight color is a variante of blue. But in the code i use itemmousedown, and i don't understand why the bar changed color only by passing by the mouse? how can i put it only highlight only in mouse click?
What about highlight: false?
If you just want the bar to be highlighted by a click, you should add a listener which highlights it on clicking the bar.