chartjs-plugin-annotations not displayed in angular 5 - angular5

While using the chart.js and the plugin chartjs-plugin-annotation, annotations are not showing while using angular 5, no error messages are displayed.
I have created a cut down example of code that exhibits the problem
console.log(Chart.plugins) shows the plugin looks to be registered as plugin[3] however it doesn't have an id as the inbuilt ones do, is this a problem?
chart.component.ts
import { Component, Inject } from '#angular/core';
import { Chart } from 'chart.js';
import 'chartjs-plugin-annotation';
#Component({
selector: 'app-chart-component',
templateUrl: './chart.component.html'
})
export class ChartComponent {
public currentCount = 0;
chart : Chart ; // This will hold our chart info
simpleChart() {
console.log(Chart.plugins);
this.chart = new Chart('canvas', {
type: 'line',
data: {
labels: ['0','1','2', '3','4'],
datasets: [
{
data: [0,1,2,5,4,5],
borderColor: "#3cba9f",
fill: false,
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true,
id: 'y-axis-0'
},
]
},
plugins: {
annotation: {
annotations: [{
type: 'line',
id: 'hLine',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: 2.5, // data-value at which the line is drawn
borderWidth: 2.5,
borderColor: 'black'
}]
}
}
}
});
}
ngOnInit() {
this.simpleChart();
}
}
Any assistance would be greatly appreciated.

I had some fun trying to get annotations working - in case you haven't already solved it, try this...
Change your imports statement to:
import * as ChartAnnotation from 'chartjs-plugin-annotation';
Change ngOnInit() to:
ngOnInit() {
let namedChartAnnotation = ChartAnnotation;
namedChartAnnotation["id"]="annotation";
Chart.pluginService.register( namedChartAnnotation);
this.simpleChart();
}
Lastly, I believe the annotation object is supposed to be a child of options, not plugins. Mine looks like this:
"options": {
"legend": {
"display": true
},
"scales": {
"xAxes": [{
"display": true
}
],
"yAxes": [{
"display": true,
"ticks": {
"min": 0,
"max": 40
}
}
]
},
"tooltips": {
"enabled": true,
"backgroundColor": "#eee",
"titleFontColor": "#000"
},
"annotation": {
"annotations": [{
"type": "box",
"xScaleID": "x-axis-0",
"yScaleID": "y-axis-0",
"yMin": 0,
"yMax": 15,
"xMin": 864,
"xMax": 1285,
"borderWidth": 1,
"backgroundColor": "rgba(200,60,60,0.25)",
"borderColor": "rgba(200,60,60,0.25)"
}, {
"type": "box",
"xScaleID": "x-axis-0",
"yScaleID": "y-axis-0",
"yMin": 30,
"yMax": 40,
"xMin": 864,
"xMax": 1285,
"borderWidth": 1,
"backgroundColor": "rgba(60,60,200,0.25)",
"borderColor": "rgba(60,60,200,0.25)"
}
]
}
}
Makes for a pretty graph :)
(except I got the colours bass ackwards! Oops!)

As an adition of what Ade said. You can also add the plugin this way
import { ChartOptions } from 'chart.js';
import * as ChartAnnotation from 'chartjs-plugin-annotation';
this.chart = new Chart('canvas', {
...
options: {
...
annotation: { ... }
} as ChartOptions,
plugins: [ChartAnnotation]
});
Adding the {...} as ChartOptions makes that TypeScript doesn't complain

To anyone having a TypeScript error saying that annotation isn't a ChartOptions property. After looking for an answer for a week or two I found a way to fix the issue.
Follow this path: node_modules/#types/chart.js/index.d.ts
Open index.d.ts, locate interface ChartOptions {
and add this line.
annotation?: Object;
}
This is how I fixed my issue after every other solution failed.

I have the same problem recently, I fixed it by registerPlugin under constructor.
Here is my solution:
import the plugin to your component:
import * as annotations from 'chartjs-plugin-annotation';
add this line to your constructor:
constructor(...) { BaseChartDirective.registerPlugin(annotations);}
If you are using typescript you may need to extend the ChartOptions interface with annotation:
interface CustomizeChartOptions extends ChartOptions {
annotation?: any
}
config your chartOptions with annotation
public barChartOptions: CustomizeChartOptions = {
// your other ChartOptions setting here
annotation: {
annotations: [
{
drawTime: "afterDatasetsDraw",
type: 'line',
mode: 'vertical',
scaleID: 'x-axis-0',
value: '1 Dec',
borderColor: 'red',
borderWidth: 2,
label: {
content: 'CURRENT',
enabled: true,
position: 'top'
}
}
]
}
};

I know I am late, but, as of now (ng2-charts 3.0.11), these answers are not working as the API changed. The annotation configuration must now be in plug-ins.
The annotation plug-in must be registered before being used.
Here is what i found, from the examples:
in app.module.ts:
import { NgChartsModule } from 'ng2-charts';
import { default as Annotation } from 'chartjs-plugin-annotation'
// ...
imports: [
//...
NgChartsModule.forRoot({
defaults: {},
plugins: [ Annotation ]
}),
// ...
and then, in your component.ts file:
chartOptions: ChartConfiguration['options'] = {
scales: {
// ...
},
plugins: {
annotation: {
annotations: [
{
type: 'line',
scaleID: 'y',
value: 16,
borderColor: 'green',
borderWidth: 6
},
]
}
},
}

Related

How can I customize vue2-editor toolbar?

I wrapped VueEditor component and followed what was written here to add font family selection to my toolbar.
<template>
<VueEditor
v-bind="$attrs"
v-on="$listeners"
:editor-toolbar="customToolbar"
/>
</template>
<script>
import { VueEditor, Quill } from 'vue2-editor'
const fonts = Quill.import('formats/font')
export default {
components: {
VueEditor
},
data () {
return {
customToolbar: [
[
{ header: [false, 1, 2, 3, 4, 5, 6] }
],
['bold', 'italic', 'underline', 'strike'],
[
{ align: '' },
{ align: 'center' },
{ align: 'right' },
{ align: 'justify' }
],
['blockquote', 'code-block'],
[
{ list: 'ordered' },
{ list: 'bullet' },
{ list: 'check' }
],
[
{ indent: '-1' },
{ indent: '+1' }
],
[
{ color: [] },
{ background: [] }
],
['link', 'image', 'video'],
['clean'],
[
{ font: fonts.whitelist }
]
]
}
}
}
</script>
I have several questions:
How can I change font family selection position? I want to have it right after heading selection.
Why do I only have two font families available? (Serif and Monospace)
How can I add font size selection to my toolbar?

Annotations are not displayed in Chart.js

I'm sorry for my poor English.
I'm trying to display a horizontal line in a graph using vue-chartjs and chartjs-plugin-annotation.
The graph appears and the options are applied, but the horizontal line does not appear because the settings in the annotation are not working.
If anyone knows how to fix this, please let me know.
The version and code is as follows
Chart.js v2.9.4
chartjs-plugin-annotation v0.5.7
Chart.js
import { Bar } from 'vue-chartjs'
import chartjsPluginAnnotation from 'chartjs-plugin-annotation'
export default {
extends: Bar,
props: ["chartData", "options"],
mounted() {
this.addPlugin(chartjsPluginAnnotation),
this.renderChart(this.chartData, this.options)
}
}
**Vue**
<template>
<Chart :chartData="chartItems" :options="chartOptions"/>
</template>
<script>
import Chart from './Chart.js'
export default {
components: {
Chart
},
data() {
return {
chartItems: {
labels: ["12月", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月"],
datasets: [{
label: "月ごとの数",
data: [9500, 12000, 19000, 15000, 9500, 5000, 10000, 14000, 9500, 8000, 4500, 7000],
backgroundColor: 'lightblue'
}]
},
chartOptions: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true,
gridLines: {
display:false
}
}],
yAxes: [{
display: true,
id: 'y-axis-0',
position: 'right',
ticks: {
beginAtZero: true,
maxTicksLimit: 5,
userCallback: (label, index, labels) => label.toLocaleString()
},
}]
},
annotation: {
annotations: [{
type: 'line',
id: 'hLine',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: 9000,
borderWidth: 2,
borderColor: 'black'
}]
},
tooltips: {
enabled: false
},
animation: {
duration: 0
}
}
}
}
}
</script>
It seems like there might be problems with the annotations library in chartjs 2.9.4, try downgrading to 2.9.3
Git issue: https://github.com/chartjs/chartjs-plugin-annotation/issues/276

How to correctly pass array with data to a chart from the VueApexCharts library in vue3?

I am writing a small covid project and trying to plot confirmed infection data using ApexCharts, but the graph is not showing. I enter the data from vuex in two tables. The data is valid however it comes from api and sa in the proxy object. What am I doing wrong? (I am using ApexCharts because vue Chartjs is not compatible with vue 3).
<template>
<apexchart width="500" type="bar" :options="options" :series="series"></apexchart>
</template>
<script>
import VueApexCharts from "vue3-apexcharts";
export default {
components: {
apexchart: VueApexCharts,
},
data(){
return {
series: [],
options: {
chart: {
type: "bar",
height: 400,
stacked: true
},
plotOptions: {
bar: {
horizontal: false
}
},
dataLabels: {
enabled: false
},
tooltip: {
shared: true,
followCursor: true
},
stroke: {
width: 1,
colors: ["#fff"]
},
fill: {
opacity: 1
},
legend: {
position: "top",
horizontalAlign: "center",
offsetX: 40
},
colors: ["rgb(95, 193, 215)", "rgb(226, 37, 43)", "rgb(94, 181, 89)"]
}
};
},
computed: {
getDate(){
return this.$store.getters['chart/getDate'];
},
getConfirmed(){
return this.$store.getters['chart/getConfirmed'];
}
},
methods: {
fillDate(){
this.options = {
xaxis: {
categories: this.getDate
}
}
this.series = [
{
name: 'Confirmed',
data: this.getConfirmed
}
];
}
},
async mounted() {
await this.fillDate();
}
}
The data from the vuex store are two arrays.
Proxy
[[Handler]]: Object
[[Target]]: Array(45)
[[IsRevoked]]: false
Instead of using mounted hook and method try to watch the computed properties then update the data based on that ones:
computed: {
getDate(){
return this.$store.getters['chart/getDate'];
},
getConfirmed(){
return this.$store.getters['chart/getConfirmed'];
}
},
watch:{
getDate:{
handler(newVal){
this.options = {
xaxis: {
categories: this.getDate
}
},
deep:true
},
getConfirmed:{
handler(newVal){
this.series = [
{
name: 'Confirmed',
data: this.getConfirmed
}
];
},
deep:true
}
}

Error in mounted hook: "TypeError: Cannot read property 'type' of null"

I am using echarts to draw a Heatmap
But giving me error!!
Error in mounted hook: "TypeError: Cannot read property 'type' of null"
mounted() {
this.initChart()
},
I am using the json data from here:
https://www.echartsjs.com/data/asset/data/hangzhou-tracks.json
Just took 1 data from the above link.
<template>
<div
:id="id"
:class="className"
:style="{height:height,width:width}"
/>
</template>
<script>
import echarts from 'echarts'
import resize from '../mixins/resize'
export default {
mixins: [resize],
props: {
className: {
type: String,
default: 'chart'
},
id: {
type: String,
default: 'newCustomerForecastChart'
},
width: {
type: String,
default: '200px'
},
height: {
type: String,
default: '200px'
}
},
data() {
return {
chart: null,
dataArr: [
{
"coord":
[
120.14322240845,
30.236064370321
],
"elevation": 21
},
{
"coord":
[
120.14280555506,
30.23633761213
],
"elevation": 5
}
]
}
},
mounted() {
this.initChart()
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose()
this.chart = null
},
methods: {
initChart() {
var points = [
{
"coord":
[
120.14322240845,
30.236064370321
],
"elevation": 21
},
{
"coord":
[
120.14280555506,
30.23633761213
],
"elevation": 5
}
]
this.chart = echarts.init(document.getElementById(this.id))
var colors = ['#5793f3', '#d14a61', '#675bba'];
this.chart.setOption({
animation: false,
bmap: {
center: [120.13066322374, 30.240018034923],
zoom: 14,
roam: true
},
visualMap: {
show: false,
top: 'top',
min: 0,
max: 5,
seriesIndex: 0,
calculable: true,
inRange: {
color: ['blue', 'blue', 'green', 'yellow', 'red']
}
},
series: [{
type: 'heatmap',
coordinateSystem: 'bmap',
data: points,
pointSize: 5,
blurSize: 6
}]
});
var bmap = myChart.getModel().getComponent('bmap').getBMap();
bmap.addControl(new BMap.MapTypeControl());
}
}
}
</script>
What is the problem actually?
should use
import * as echarts from 'echarts'
imstead of
import echarts from 'echarts'

Why echarts are not showing on I.E-11 version

I had created a project using vuejs+Vue-CLI and integrated echarts in it. Echarts are working well in all browsers but when I open it in IE-11 version, page can't load and it shows following error:
[object Error]{description: "Expected ')'", message: "Expected ')'", name: "SyntaxError", number: -2146827282, stack: "SyntaxError...", Symbol()_n.kyufm4c0tec: undefined, Symbol()_p.kyufm4c0tec: undefined, Symbol()_q.kyufm4c0tec: undefined, Symbol()_r.kyufm4c0tec: undefined, Symbol(Lang fallback)_m.kyufm4c0tec: undefined, Symbol(util.promisify.custom)_o.kyufm4c0tec: undefined}
Here is my code:
<template>
<ECharts :options="pie" style="width:300px; height:260px">
</ECharts>
</template>
<script>
import ECharts from "vue-echarts/components/ECharts.vue";
import "echarts/lib/chart/pie";
import "echarts/lib/component/title";
export default {
components: {
ECharts
},
data() {
return {
pie: {
backgroundColor: "transparent",
tooltip: {
trigger: "item",
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
series: [{
name: "Product Sales",
type: "pie",
radius: ["50%", "70%"],
avoidLabelOverlap: false,
data: [{
value: 1,
name: "Product A"
},
{
value: 2,
name: "Product B"
},
{
value: 3,
name: "Product C"
}
],
label: {
normal: {
show: false,
position: "center"
},
emphasis: {
show: true,
textStyle: {
fontSize: "20",
fontWeight: "bold"
}
}
},
labelLine: {
normal: {
show: false
}
}
}]
}
};
}
};
</script>
what's an issue in IE browser I also searched for the solution and tried it but did't get the result.
Versions:
echarts-4.1.0,
vue-echarts: 3.1.1
Any help will be appreciated! Thanks
The documentation of vue-echarts-v3 does not inform it, but you have to add the echarts on your webpack (or any other bundler you are using) configuration as well.
{
test: /\.js$/,
loader: 'babel-loader',
include: [
resolve('src'),
resolve('test'),
resolve('node_modules/vue-echarts-v3/src'), // Their suggestion https://www.npmjs.com/package/vue-echarts-v3
resolve('node_modules/echarts/lib'), // Not suggested, but required as well
]
},