How to always show line chart tooltip in ionic-angular.? - ionic-framework

i am working on chart.js in ionic with angular and i am generating a chart which is line chart , i dnt want to show dots for each point and show tooltip on hover i want to show values alway without hover, i tried many ways which are mentioned on stackover flow as well but none of them working so i thought to share my code
following is my code
import { Component, OnInit, ViewChild, ElementRef } from "#angular/core";
import { Chart } from "chart.js";
#Component({
selector: 'app-bp',
templateUrl: './bp.page.html',
styleUrls: ['./bp.page.scss'],
})
export class BpPage implements OnInit {
#ViewChild("barCanvas") barCanvas: ElementRef;
private barChart: Chart;
constructor() {}
ngOnInit() {
setTimeout(() =>{
this.barChart = new Chart(this.barCanvas.nativeElement, {
type: "line",
data: {
labels: ["12-Apr", "13-Apr", "14-Apr", "15-Apr", "16-Apr", "17-Apr", "18-Apr"],
datasets: [{
label: "High",
backgroundColor: "#3e95cd",
borderColor: "#3e95cd",
pointBorderWidth: 10,
pointHoverRadius: 10,
data: [10943, 29649, 6444, 2330, 36694, 10943, 29649],
fill: false,
borderWidth: 3
}, {
label: "Low",
backgroundColor: "#ff3300",
borderColor: "#ff3300",
pointBorderWidth: 10,
pointHoverRadius: 10,
data: [9283, 1251, 6416, 2374, 9182, 9283, 1251],
fill: false,
borderWidth: 3
}]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
},
},
});
},1500);
}
}

To always show the tooltips, you must follow an approach similar to the one described here: Chart.js v2: How to make tooltips always appear on pie chart?
You have to define for your chart the showAllTooltips option as below:
let barChart = new Chart(this.barCanvas.nativeElement, {
type: "line",
//...
//...
},
options: {
showAllTooltips: true,
//...
}
});
And than you must call the code that defines the showAllTooltips behavior.
Here is a stackblitz of the working solution.
The method configureTooltipBehavior() is the one responsible for the magic.
https://stackblitz.com/edit/angular-ivy-fzpyva

Related

antd column chart: label value is displayed outside of chart

I have a fairly simple ant column chart, this is it:
import React from "react";
import ReactDOM from "react-dom";
import { Column } from "#ant-design/plots";
const DemoColumn = () => {
const data = [
{
type: "Value 1",
value: 315801
},
{
type: "Value 2",
value: 222095
},
{
type: "Value 3",
value: 10800
}
];
const config = {
data,
loading: data.length === 0,
xField: "type",
yField: "value",
seriesField: "type",
yAxis: {
label: {
formatter: (v) => v
}
},
xAxis: false,
height: 200,
autoFit: false,
legend: {
position: "bottom",
flipPage: false
},
interactions: [
{
type: "element-active"
}
],
label: {
position: "top",
offsetY: 8,
formatter: ({ value }) => value
}
};
return <Column {...config} />;
};
ReactDOM.render(<DemoColumn />, document.getElementById("container"));
The problem is, that the number of Value 1 is hanging off the chart. I tried setting the padding but this did not help, it acutally screwed the whole chart up?!?
Here is also a fiddle: https://codesandbox.io/s/cool-microservice-gbrbm9?file=/index.js:0-929
Fixed it myself by adding
appendPadding: 10
There is an Open Bug in AntD GitHub [BUG] Label of column charts are being cut out if label position is set to 'top' officials for this issue. Some member of ant design team has given an answer as set limitInPlot: true in config. I tried that but didn't work.
I tried with adjusting height prop and offsetY in lable prop inside config. This is just tricky option for you to achieve what you want.
Option 1 -
label: {
position: "top",
offsetY: 15, // change offset to this then value will not crop as before but just overlap with chart.
formatter: ({ value }) => value
}
Option 2 -
xAxis: false,
height: 750, // increase the chart height and it will show the value with a gap. But this will create a scroll.
autoFit: false,
Option 3 -
You can use mix of above two options with adjusting right values. This will get what you want without a scroll. below values got this result.
xAxis: false,
height: 500, // adjust height
autoFit: false,
legend: {
position: "bottom",
flipPage: false
},
interactions: [
{
type: "element-active"
}
],
label: {
position: "top",
offsetY: 12, // adjust offset
formatter: ({ value }) => value
}
This is the sandboxcode.
Hope this will help to overcome your issue.

Attach a custom plugin to Vue-Chart

We need to attach a custom plugin to vue-chart. Please guide us how to implement on the same
import { Line, mixins } from 'vue-chartjs'
export default {
namespaced: true,
extends: Line,
props: ['chartData', 'options'],
mounted() {
this.renderChart(this.chartData, this.chartData.options)
}
}
This is how we are using the line chart of Vue-chart. How to attach the plugin here
https://blog.larapulse.com/javascript/creating-chart-js-plugins
We want to try this. But since we are using vue-chart which internally uses chart.js. Need some help to attach the plugin. please guide us
I want to apply some background color to the chart for one specific column in the chart
vue-chart-js provide method to attach plugins. Use this way:
import the plugin
import ChartDataLabels from 'chartjs-plugin-datalabels';
then, call addPlugin in mounted
mounted() {
this.addPlugin(ChartDataLabels);
this.renderChart(
this.chartData,
this.options,
);
}
Below is PieChart.vue script in case you create pie chart :
<script>
import { Pie, mixins } from 'vue-chartjs';
import ChartDataLabels from 'chartjs-plugin-datalabels';
Chart.plugins.unregister(ChartDataLabels);
const { reactiveProp } = mixins;
export default {
extends: Pie,
mixins: [reactiveProp],
props: {
options: {
type: Object,
default: null,
},
},
mounted() {
this.addPlugin(ChartDataLabels);
this.renderChart(
this.chartData,
this.options,
);
},
};
</script>
Using the annotation plugin for Chart.js as example, you can use the addPlugin function to attach it:
import { Line, mixins } from 'vue-chartjs'
import chartjsPluginAnnotation from "chartjs-plugin-annotation"
export default {
namespaced: true,
extends: Line,
props: ['chartData', 'options'],
mounted() {
//Arguments is an Array of Plugins (https://vue-chartjs.org/api/#addplugin)
this.addPlugin([chartjsPluginAnnotation]),
this.renderChart(this.chartData, this.chartData.options)
}
}
After this just pass the plugin's options on your component as usual. In this case, if you wanted to draw a vertical line, it would be something like this:
computed: {
chart() {
return {
chartData: {
labels: this.data.labels,
datasets: [
{
label: "Score",
data: this.data.data
}
],
options: {
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
borderColor: "#4ecca3",
value: parseInt(this.data.line),
borderDash: [4, 4],
label: {
content: this.data.line,
enabled: true,
position: "top",
xAdjust: 15,
backgroundColor: '#4ecca3',
fontSize: 10,
}
}
]
}
},
}
};
}
import chartjsPluginAnnotation from "chartjs-plugin-annotation";
And:
mounted() {
Chart.plugins.register(chartjsPluginAnnotation);
this.addPlugin(chartjsPluginAnnotation);
this.renderChart(this.chartData, this.options);
}

Vue-chartjs is rendering my responsive chart too tall for my window

I created a simple responsive HTML + JS chart with chart.js which worked well. I decided to do it within Vue CLI and so have tried to switch it to vue-chartjs but the same chart always renders about 33% taller than my window and so presents vertical scrollbars (the width is fine). I recreated the problem with a sample trivial graph which I render with:
import {Line} from 'vue-chartjs'
export default {
extends: Line,
mounted () {
this.renderChart(data, options)
}
}
Note the data is trivial and the options are {}.
If I use chart.js in my Vue component, instead of vue-chartjs then it works fine. I.e. I do nothing more than delete the above code from my component and change it to the following then it renders fine, just like my sample HTML + chart.js version.
import Chart from 'chart.js'
function mount(el) {
return new Chart(
document.getElementById(el).getContext('2d'), {
type: 'line',
data: data,
options: options,
})
}
export default {
template: '<canvas id="chart"></canvas>',
mounted () {
self.chart = mount('chart')
}
}
I am using the default responsive: true and maintainAspectRatio: false of course, and have no explicit CSS or size settings anywhere.
Why can I not get the chart to render the height correctly when I use vue-chartjs? I am using vue-chartjs version 3.4.2 but have also tried a few versions back. I have looked all over the github bug tracker but seen nothing related.
UPDATE:
You should pass the options as prop or locally. But it's needed to add:
responsive: true
maintainAspectRatio: false
the desired height as well as the options as you said. Here's how it worked for me:
options:
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}]
},
responsive: true,
maintainAspectRatio: false
}
In template:
<bin-graph-weight :chart-data="datacollection" :styles="myStyles" :options="datacollection.options"/>
graph-component.js:
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins
export default {
extends: Line,
mixins: [reactiveProp],
props: ['options'],
mounted () {
// this.chartData is created in the mixin.
this.renderChart(this.chartData, this.options)
},
// If you want to pass options please create a local options object
watch: {
chartData () {
this.$data._chart.update()
}
}
}
Also had problem with height overflow and responsiveness, fixed by introducing flex parent container that takes up 100% of the space. After setting responsive and ratio options (check out related chartjs doc):
options: {
// ..
responsive: true,
maintainAspectRatio: true
}
I used following css to fill 100% of the parent (where TheChart is vue-chartjs component. Basically need to make sure the chart's parent is always filling 100% of it's own parent):
vue template
<v-container class="chart-container">
<TheChart :chartdata="chartData" :options="chartOptions" />
</v-container>
scss:
.chart-container {
flex-grow: 1;
min-height: 0;
> div {
position: relative;
height: 100%;
}
}
With responsiveness the chart rerenders with promises and actually sets two times.
With a watcher in Vue.js you can rerender every time with changes in the chartData.
Chart component:
<script>
import { Bar, mixins } from 'vue-chartjs';
const { reactiveProp } = mixins;
export default {
extends: Bar,
mixins: [reactiveProp],
props: ['chartOptions'],
mounted() {
this.renderChart(this.chartData, this.chartOptions);
},
watch: {
chartData() {
this.renderChart(this.chartData, this.chartOptions);
},
},
};
</script>
Use together with dynamic styles.
Chart properties:
<template>
<div style="height:300px;">
<bar-chart :styles="myStyles" :chart-data="dataCollection"
:chart-options="chartOptions"></bar-chart>
</div>
</template>
<script>
import BarChart from './ChartBar.vue';
export default {
components: {
BarChart,
},
props: ['dataCollection'],
data() {
return {
myStyles: {
height: '300px',
width: '100%',
position: 'relative',
},
chartOptions: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
gridLines: {
display: true,
},
}],
xAxes: [{
ticks: {
beginAtZero: true,
},
gridLines: {
display: false,
},
}],
},
legend: {
display: true,
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label(tooltipItems, data) {
const { datasetIndex, index } = tooltipItems;
const value = data.datasets[datasetIndex].data[index];
if (parseInt(value, 10) > 999) {
return ` ${value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;
}
return ` ${value}`;
},
},
},
responsive: true,
maintainAspectRatio: false,
height: 300,
},
};
},
};
</script>
<style lang="scss" scoped>
</style>

Chart.js place both series on same scale

So I have a chart.js chart with two series. One is a bar chart and the other is a line graph.
S1 = 71,166,2,6,8
S2 = 6,2,4,8,5
When I plot them, they both appear on their own scales which makes the bar and line graphs kinda pointless.
I need a way to plot both charts on the same scale.
Is there a way to do this within chart.js? If not, how would you do it?
thanks.
var barChartData = {
labels: dataLabels,
datasets: [{
type: 'bar',
label: "Actual",
data: dataActual,
fill: false,
backgroundColor: '#71B37C',
borderColor: '#71B37C',
hoverBackgroundColor: '#71B37C',
hoverBorderColor: '#71B37C',
yAxisID: 'y-axis-2'
}, {
label: "Maximum",
type:'line',
data: dataMaximum,
fill: false,
borderColor: '#EC932F',
backgroundColor: '#EC932F',
pointBorderColor: '#EC932F',
pointBackgroundColor: '#EC932F',
pointHoverBackgroundColor: '#EC932F',
pointHoverBorderColor: '#EC932F',
yAxisID: 'y-axis-1'
} ]
};
$(function () {
if (theChart !== undefined) {
theChart.destroy();
}
var ctxActualVsMax = document.getElementById("myChart2").getContext("2d");
theChart = new Chart(ctxActualVsMax, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
tooltips: {
mode: 'label'
},
elements: {
line: {
fill: false
}
},
scales: {
xAxes: [{
display: true,
gridLines: {
display: false
},
labels: {
show: true,
}
}],
yAxes: [{
type: "linear",
display: true,
position: "left",
id: "y-axis-1",
gridLines:{
display: false
},
labels: {
show:true,
}
}, {
type: "linear",
display: false,
position: "right",
id: "y-axis-2",
gridLines:{
display: false
},
labels: {
show:true,
}
}]
}
}
});
});
In your code you have specified your two datasets to use different yAxisId's. Just set them both to the same, you can also remove the unused yAxes object from the options
fiddle

redraw funnel chart in highchart when a segment is removed?

Is there a way funnel chart will redraw like pie chart does, when a segment is removed?
Similar to this question redraw pie chart in highchart
http://jsfiddle.net/2Me2z/
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
plotOptions: {
pie: {
showInLegend: true
}
},
legend: {
enabled: true
},
series: [{
data: [20, 30, 30, 20]
}]
});
// button handler
$('#button').click(function() {
var series = chart.series[0];
if (series.data.length) {
chart.series[0].data[0].remove();
}
});
});
So click on any slice in legend will cause the chart to redraw and the remaining slices will take up 100%
Wonder if the same thing can be done for a funnel chart
http://jsfiddle.net/YUL5c/2/
$(function () {
var chart;
$(document).ready(function () {
// Build the chart
$('#container').highcharts({
chart: {
type: 'funnel',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
series: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.01]
]
}]
});
});
});
Currently the segment just disaapear. But the chart does not redraw
Unfortunately this animation is not supported, but I advice to post your request on the uservoice website
point.visible flag is ignored in funnel code.
If adding the check back to the drawing logic things just work magically. Even for the animation.
Not sure if it is a bug or ignored by intention