i have been trying to use the Chart.js in Ionic 5 by looking this tutorial (https://ichi.pro/es/ionic-5-charts-graphs-usando-la-biblioteca-chartjs-102145521332905)
But I get this error:
The code is almost identical except for the file names.
Don't really understand why it happens, any help is welcome.
import { Component, AfterViewInit, ViewChild , ElementRef } from '#angular/core';
import {Chart} from "chart.js";
#Component({
selector: 'app-tab3',
templateUrl: 'tab3.page.html',
styleUrls: ['tab3.page.scss']
})
export class Tab3Page implements AfterViewInit{
#ViewChild('lineCanvas') private lineCanvas: ElementRef;
lineChart: any;
constructor() { }
ngAfterViewInit() {
this.lineChartMethod();
}
lineChartMethod() {
this.lineChart = new Chart(this.lineCanvas.nativeElement, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'November', 'December'],
datasets: [
{
label: 'Sell per week',
fill: false,
//lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40, 10, 5, 50, 10, 15],
spanGaps: false,
}
]
}
});
}
}
Here's the HTML
<ion-content [fullscreen]="true">
<div class="ion-padding">
<ion-card>
<ion-card-header>
Line Chart
</ion-card-header>
<ion-card-content>
<canvas #lineCanvas style="position: relative; height:20vh; width:40vw"></canvas>
</ion-card-content>
</ion-card>
</div>
</ion-content>
Chart.js need to register the controller before loading datas,but whatever the underneath mechanics, here is from the chart.js docs the proper way to init Chart in typescript :
A short registration format is also available to quickly register
everything.
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
And finally there is an separate
path to do just the above for you, in one line:
import Chart from 'chart.js/auto';
source :https://www.chartjs.org/docs/master/getting-started/integration.html
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
Just put this...
Related
In Apache Echarts, is there a way to rotate the title text of a chart so that it is vertically oriented on one side rather than horizontal on the top? The title at the top sometimes takes important chart real-estate that my series in some cases can overlap. I would like to instruct Echarts when there's a space crunch to move the title off to the left side in a vertical position (like reading titles on the spines of books in a library). There appears to be several "rotate" options for labels, but nothing for titles.
I am not sure you can rotate the main title if you use the default canvas renderer. In this case, you may want to play with the name of your yAxis like this:
const myChart = echarts.init(document.getElementById('main'));
let option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value',
name: 'This is my title',
nameLocation: 'center',
nameRotate: 90,
nameGap: 45,
nameTextStyle: {
color: 'black',
fontSize: 18,
fontWeight: 'bold'
}
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
myChart.setOption(option);
#main {
width: 100%;
height: 350px;
}
<script src="https://cdn.jsdelivr.net/npm/echarts#5.4.1/dist/echarts.min.js"></script>
<div id="main"></div>
Alternatively, you could use the SVG renderer and add a bit of CSS to transform the main title (which is a <text> element):
const myChart = echarts.init(document.getElementById('main'), null, { renderer: 'svg' });
let option = {
title: {
text: 'This is my title'
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
myChart.setOption(option);
#main {
width: 100%;
height: 350px;
}
svg g text:last-child {
transform: rotate(-90deg) translateX(-250px);
}
<script src="https://cdn.jsdelivr.net/npm/echarts#5.4.1/dist/echarts.min.js"></script>
<div id="main"></div>
I am working with Nextjs 13, chart.js v4.0.1 and react-chartjs-2 v5.0.1.
I could succesfully plot graph with a classic scale, but now that I am trying with x axis in serie, I have a weird error "Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused."
Do you have any idea why this occur ? This is my sample code :
"use client";
import React from "react";
import { Chart as ChartJS, TimeScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from "chart.js";
import { Line } from "react-chartjs-2";
ChartJS.register(TimeScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend);
export const options = {
plugins: {
legend: {
position: "bottom" as const,
},
title: {
display: false,
// text: "Chart.js Line Chart",
},
},
response: true,
scales: {
x: {
type: "time",
time: {
unit: "day",
},
},
},
maintainAspectRatio: false,
};
export const data = {
datasets: [
{
label: "Estimation",
data: [
{
x: new Date("2020-01-01"),
y: 50,
},
{
x: new Date("2020-01-02"),
y: 60,
},
],
borderColor: "rgb(255, 99, 132)",
backgroundColor: "rgba(255, 99, 132, 0.5)",
tension: 0.25,
},
],
};
export default function Kikoo() {
return (
<div className="relative px-4 py-8" style={{ margin: "auto", width: "100%", height: "100%" }}>
<Line options={options} data={data} />
</div>
);
}
Thank you so much in advance, I am seriously stuck on that one :/
I am working on a project and we are using a chart created with chart js. I want to give the legend a background color (the top part thats drawn in the image). After a lot of searching on the internet i stil havent found a solution to my problem so i thought lets try stack overflow. can some one help me Please??>!
the part i want to give a background color
here is part of my code
enter code here
<div>
<canvas id="myChart"></canvas>
</div>
<script>
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
You can use a custom plugin for this:
const plugin = {
id: 'legendBackground',
beforeDraw: (chart, args, opts) => {
const {
chartArea: {
width,
top,
left
},
ctx
} = chart;
ctx.fillStyle = opts.color || 'transparent';
ctx.fillRect(left, 0, width, top)
}
}
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange'
}]
},
options: {
plugins: {
legendBackground: {
color: 'pink'
}
}
},
plugins: [plugin]
}
const 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/3.7.1/chart.js"></script>
</body>
I am using echarts library for bar charts. I want scrollbar to display outside the canvas. Is there any way I can accomplish this?
Unfortunately, Echarts don't support scrollbar option.
However you can simply achieve this use a wrap DOM.
check this demo:
let echartsObj = echarts.init(document.querySelector('#canvas1'));
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar'
}]
};
echartsObj.setOption(option)
echartsObj = echarts.init(document.querySelector('#canvas2'));
option = {
xAxis: {},
yAxis: {},
series: [{
symbolSize: 20,
data: [
[10.0, 8.04],
[8.0, 6.95],
[13.0, 7.58],
[9.0, 8.81],
[11.0, 8.33],
[14.0, 9.96],
[6.0, 7.24],
[4.0, 4.26],
[12.0, 10.84],
[7.0, 4.82],
[5.0, 5.68]
],
type: 'scatter'
}]
};
echartsObj.setOption(option)
.echart-wrap {
display: inline-block;
width: 300px;
height: 300px;
overflow: scroll;
border: 1px solid black;
}
<html>
<header>
<script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.min.js"></script>
</header>
<body>
<div class="echart-wrap">
<div id="canvas1" style="width: 500px; height: 500px">
</div>
</div>
<div class="echart-wrap">
<div id="canvas2" style="width: 500px; height: 500px">
</div>
</div>
</body>
</html>
This question already has answers here:
Chart.js not showing in Angular2 if it doesn't exist on the main page
(2 answers)
Closed 6 years ago.
I am trying to create Bar Chart using this github repo. But my chrome does not display chart.
Here is my plnkr. I don't know what i am doing wrong.
Here is my updated code:
app.ts
import {Component, Pipe, PipeTransform} from 'angular2/core';
import {CORE_DIRECTIVES, NgClass, FORM_DIRECTIVES, Control, ControlGroup, FormBuilder, Validators} from 'angular2/common';
import {CHART_DIRECTIVES} from './ng2-charts.ts';
#Component({
selector: 'my-app',
templateUrl: 'mytemplate.html',
directives: [CHART_DIRECTIVES, NgClass, CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class AppComponent {
constructor() {
console.log('bar demo');
}
private barChartOptions = {
scaleShowVerticalLines: false,
responsive: true,
multiTooltipTemplate: '<%if (datasetLabel){%><%=datasetLabel %>: <%}%><%= value %>'
};
private barChartLabels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
private barChartSeries = ['Series A', 'Series B'];
public barChartType = 'Bar';
private barChartLegend:boolean = true;
private barChartData = [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
];
// events
chartClicked(e:any) {
console.log(e);
}
chartHovered(e:any) {
console.log(e);
}
}
app.html
<base-chart class="chart"
[data]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[series]="barChartSeries"
[legend]="barChartLegend"
[chartType]="barChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></base-chart>
Suggest me if there is any another library for displaying data on the bar chart for angular2.
Eleboration of #Thierry's answer with example.
updated code is here:
app.ts
import {Component, DynamicComponentLoader, Injector} from 'angular2/core';
import {CORE_DIRECTIVES, NgClass, FORM_DIRECTIVES, Control, ControlGroup, FormBuilder, Validators} from 'angular2/common';
import {ChartDirective} from './charts.ts';
#Component({
selector: 'my-app',
templateUrl: 'mytemplate.html',
directives: [ChartDirective, NgClass, CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class AppComponent {
constructor() {
}
}
app.html
<div class="container details-container">
<topics></topics>
</div>
<div class="graph-container">
<div class="row no-pad" style="position: relative;">
<div style="margin-left:14px; z-index: 100; height: 250px;">
<canvas id="myChart" chart height="250" width="350"></canvas>
</div>
</div>
</div>
chart.ts
import {Directive, ElementRef, Renderer, Input} from 'angular2/core';
#Directive({
selector: '[chart]'
})
export class ChartDirective {
constructor(el: ElementRef, renderer: Renderer) {
//el.nativeElement.style.backgroundColor = 'yellow';
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var options = {
scaleBeginAtZero : true,scaleShowGridLines : true,
scaleGridLineColor : "rgba(0,0,0,.05)",
scaleGridLineWidth : 1,
scaleShowHorizontalLines: true,
scaleShowVerticalLines: true,
barShowStroke : true,
barStrokeWidth : 2,
barValueSpacing : 5,
barDatasetSpacing : 1,
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
}
var ctx: any = el.nativeElement.getContext("2d");
var BarChart = new Chart(ctx);
BarChart.Bar(data, options);
}
}
working plnkr http://plnkr.co/edit/Vfsert1sAJ4dsVR4MdyV?p=preview
I think that this question could help you:
Chart.js not showing in Angular2 if it doesn't exist on the main page