Angular-chart / line chart with multiple horizontal lines (margins) - angularjs

I am trying to create an agular line chart that has four horizontal lines (margins - two upper margins and two lower margins). Please see this fiddle - https://jsfiddle.net/CypressMountain/arq34fcu/30/
My objective is to define the properties (value,color,label) of these lines inside angular controller, but not inside JQuery line chart extension, as it is currently done in the fiddle. The graph properties, as well as the margin line properties will come from the back end, and the margin lines will be drawn independently from the graph.
I am not sure how to achieve something like $scope.margins = [] in controller, similar to what we have for $scope.data = [] or $scope.labels... Any help is appreciated.
This is the HTML:
<canvas id="line" class="chart chart-linebis" chart-data="data"
chart-labels="labels" chart-legend="true" chart-series="series"
chart-click="onClick">
</canvas>
The margin lines are now defined in draw function, when the line chart type is being extended
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var lines =
[
{
label: 'Upper margin 1',
value: 90,
color: 'rgba(255, 0, 0, .9)'
},
{
label: 'Upper margin 2',
value: 75,
color: 'rgba(255, 165, 0, .8)'
},
{
label: 'Lower margin 1',
value: -10,
color: 'rgba(0, 165, 255, .8)'
},
{
label: 'Lower margin 2',
value: -25,
color: 'rgba(0, 0, 255, .8)'
}
]
.............................
This is the controller:
angular.module('test', ['chart.js']);
angular.module('test').controller('TestCtrl', function ($scope) {
$scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
$scope.series = ['Series A'];
$scope.data = [
[-5, 48, 40, -19, 86, 27, 90]
];
});
Two previous posts were referenced
angular-chart add horizontal line
and
Chart.js - draw horizontal line

I finally got it resolved and hope this will help someone else who might have a similar task.
$scope.options is the place inside the angular controller where the margin lines' properties will be received from the back end and assigned to $scope.options (you would replace the current hard coded label, value, and color for each horizontal line with the dynamic values).
$scope.options = {
limitLines: [
{
label: 'Upper margin 1',
value: 90,
color: 'rgba(255, 0, 0, .9)'
},
{
label: 'Upper margin 2',
value: 75,
color: 'rgba(255, 165, 0, .8)'
},
{
label: 'Lower margin 1',
value: -10,
color: 'rgba(0, 165, 255, .8)'
},
{
label: 'Lower margin 2',
value: -25,
color: 'rgba(0, 0, 255, .8)'
}
]
}
Then the canvas tag in HTML will have the options added:
chart-options="options"
Finally, in the line chart extension code, in the draw function 'lines' will be bridged to 'limitLines' via options:
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var lines = this.options.limitLines;

Related

Chart.js (React) I need to put the labels like a paragraph, I don't want rotate labels

I using React with char.js my labels rotating 45o, But I don't want it
I need the labels in this mode similar a paragraph, the text in the overflow get down, like a ,
I tried to use:
maxRotation: 0
The labels can be multi-lines, defining each label as an array of strings:
labels: [['En diàlogos cotidianos', 'con', 'empleados'],
['En medios de', 'comunicaciòn'],
['En campanas', 'o eventos'],
'No'],
See below the snippet.
const data = {
labels: [['En diàlogos cotidianos', 'con', 'empleados'],
['En medios de', 'comunicaciòn'],
['En campanas', 'o eventos'],
'No'],
datasets: [{
label: 'Sales',
data: [10000, 20000, 30000,40000],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderWidth: 0
},{
label: 'Target',
data: [50000, 50000, 50000, 40000,],
backgroundColor:'rgba(255, 26, 104, 0.2)',
borderWidth: 0
}]
};
// config
const config1 = {
type: 'bar',
data,
options: {
scales: {
x: {
stacked: true
},
y: {
beginAtZero: true,
stacked: true
}
}
},
};
new Chart(
document.getElementById('myChart'),
config1
);
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
</body>
</html>

Change background color of every second column in Chartjs? [duplicate]

In react-chartjs-2
In Line chart every grid should have different background colors.
Is this achievable with this library?
This is how LineChart should looks:
This is my Code/configuration:
const options = {
responsive: true,
scales: {
y: {
grid: {
backgroundColor: [
'rgba(36, 206, 0, 0.8)',
'rgba(255, 255, 0, .8)',
'rgba(255, 162, 0, 0.8)',
'rgba(36, 206, 0, 0.8)',
],
},
};
Thanks for reading.
You can use an inline plugin to achieve it:
var GradientBgPlugin = {
beforeDraw: function(chart, args, options) {
const ctx = chart.ctx;
const canvas = chart.canvas;
const chartArea = chart.chartArea;
// Chart background
var gradientBack = canvas.getContext("2d").createLinearGradient(0, 250, 0, 0);
gradientBack.addColorStop(0, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.16, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.17, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.25, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.26, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.5, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.51, "rgba(251,221,221,1)");
gradientBack.addColorStop(1, "rgba(251,221,221,1)");
ctx.fillStyle = gradientBack;
ctx.fillRect(chartArea.left, chartArea.bottom,
chartArea.right - chartArea.left, chartArea.top - chartArea.bottom);
}
};
Than just include it in your Chart options:
plugins: [GradientBgPlugin]
The result should be similar to this JSFiddle.
EDIT
For Reach Charts JS 2, you need small changes in setup. You define plugin this way:
const plugins = [{
beforeDraw: function(chart) {
const ctx = chart.ctx;
const canvas = chart.canvas;
const chartArea = chart.chartArea;
// Chart background
var gradientBack = canvas.getContext("2d").createLinearGradient(0, 250, 0, 0);
gradientBack.addColorStop(0, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.16, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.17, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.25, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.26, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.5, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.51, "rgba(251,221,221,1)");
gradientBack.addColorStop(1, "rgba(251,221,221,1)");
ctx.fillStyle = gradientBack;
ctx.fillRect(chartArea.left, chartArea.bottom,
chartArea.right - chartArea.left, chartArea.top - chartArea.bottom);
}
}];
Than you plug it this way:
<Line data={data} plugins={plugins} />
You can see it working fine on CodeSandbox here.
You can write a custom inline plugin, that draws the colors on the chart Area. In the options section you can put an object with all the sections you want, from where to where and which color they need to be
Example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [100, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
plugins: {
backgrounds: {
hbars: [{
from: 28,
to: 100,
color: "rgb(195, 230, 195)"
},
{
from: 20,
to: 28,
color: "rgb(230, 220, 195)"
},
{
from: 0,
to: 20,
color: "rgb(230, 195, 195)"
}
]
}
}
},
plugins: [{
id: 'backgrounds',
beforeDraw: (chart, args, options) => {
const {
ctx,
chartArea,
scales: {
y
}
} = chart;
options.hbars.forEach((hBar) => {
ctx.save();
ctx.fillStyle = hBar.color;
ctx.fillRect(chartArea.left, y.getPixelForValue(hBar.from), chartArea.right - chartArea.left, y.getPixelForValue(hBar.to) - y.getPixelForValue(hBar.from));
ctx.restore();
})
}
}]
}
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/3.2.0/chart.js"></script>
</body>
Detailed explanation can be found here: https://medium.com/#omi10859/alternative-background-lines-in-chartjs-a626ce4d3bcb
We can use annotaion plugin with chartjs to create custom elements.
we can use annotation plugin to do this
import annotationPlugin from "chartjs-plugin-annotation";
import {Chart} from 'chart.js';
Chart.register(annotationPlugin);
this code will add a box to our chart
{
type: 'box', #type of draw
drawTime: 'beforeDraw', #this will decide background or foreground
yMin: 5, #value min on y axis
yMax: 10, #value max on y axis
borderColor: 'rgb(242, 244, 248, 0.9)', #border color of the box
borderWidth: 1, #boarder width for box
backgroundColor: '#F2F4F8', #colour of the box
}
# add option while rendering
const options = {
plugins: {annotation: {annotations: background_annotation}
}
this code render this

Dynamically add x-axis in React using ChartJS

I want to add another x axis to my ChartJS which works, but the scales do not separate, for example I want one label on the x-axis with 0-9 and another one 0-16 to show separately. It works perfectly fine for the y-axis but not for the x-axis.
Now for the code:
here I create an initial state
let state = {
labels: [],
datasets: [
{
label: 'ignore',
fill: false,
lineTension: 0,
backgroundColor: 'rgba(109, 24, 172, 1)',
borderColor: 'rgba(109, 24, 172, 1)',
borderWidth: 0.1,
pointRadius: 0.2,
data: []
}, {
label: 'ignore1',
fill: false,
lineTension: 0,
backgroundColor: 'rgba(0, 250, 255, 1)',
borderColor: 'rgba(0, 250, 255, 1)',
borderWidth: 0.1,
pointRadius: 0.2,
data: []
}
]
};
Here is my first function with 9 datapoints:
function adddataset(){
let lineChart = Chart.instances[0];
const data=lineChart.data;
const newDataset = {
label: 'Dataset ' + (data.datasets.length + 1),
backgroundColor: 'rgba(109, 24, 172, 1)',
borderColor: 'rgba(0, 250, 255, 1)',
data: [65, 59, 80, 81, 56, 55, 40],
yAxisID: 'By',
xAxisID: 'Bx',
};
lineChart.data.datasets.push(newDataset);
lineChart.update();
}
here is my second function to add a second dataset:
function adddataset1(){
let lineChart = Chart.instances[0];
const data=lineChart.data;
const newDataset = {
label: 'Dataset ' + (data.datasets.length + 1),
backgroundColor: 'rgba(rgba(109, 24, 172, 1)',
borderColor: 'rgba(109, 24, 172, 1)',
data: [100,30,50,60,20,30,60,100,34,3456,6,5,4,3,5,545],
yAxisID: 'Cy',
xAxisID: 'Cx',
};
lineChart.data.datasets.push(newDataset);
lineChart.update();
}
now here is my class where I initialize the LineGraph and have 2 buttons which call the functions
class About extends React.Component {
render() {
return (
<body>
<main>
Graph
<div className='Graph'>
<div style={{ height: 500 }}>
<Line
id="mychart"
data={state}
options={{
title: {
display: true,
text: 'Average Rainfall per month',
fontSize: 20
},
legend: {
display: true,
position: 'right'
},
maintainAspectRatio: false,
responsive: true
}}
/>
</div>
</div>
<button onClick={adddataset1}>
Button1
</button>
<button onClick={adddataset}>
Button2
</button>
</main>
</body>
);
}
}
export default About;
There are 2 solutions for your problem, you can either provide your data in object format so the labels get taken from the object like so:
const data = [{x: '1', y: 5}, {x: '2', y: 3}];
Or you can add a second x axis with the correct ID to all the scales which has a labels array property in which you can specify the labels for that scale so you will get something like this:
const myChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
myChart.options.scales['secondX'] = {
labels: ['6', '7', '8'],
position: 'bottom'
}
myChart.update();

add numeric value with different color in radar labels

I am new to chart.js. i need help in adding a numeric value to radar chart point labels with different color. eg radar label with styling
labels color should be in black.
numeric value should be in a different predefined color(eg blue).
new Chart('radar-chart', {
type: 'radar',
data: {
labels: ['mon 30', 'tue 40', 'thurs 25', 'fri 45', 'sat 67', 'sun 50'],
datasets: [{
label: 'My First Dataset',
data: [65, 59, 90, 81, 56, 55],
fill: true,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 132)',
pointBackgroundColor: 'rgb(255, 99, 132)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(255, 99, 132)'
}],
},
options: {
plugins: {
legend: {
display: false
}
},
scales: {
r: {
pointLabels: {
color: 'black',
font: {
size: 20,
style: 'italic'
}
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.min.js"></script>
<canvas id="radar-chart"></canvas>
the values near the labels in vertex should be in a predefined color(eg blue) -like the one attached in image.
please feel free to give a different approach to achieve this requirement. Thanks in advance for the help.

How to fix labels clashing problem in RGraph pie chart?

I'm creating RGraph pie chart in which labels are clashing. Though I am using labels.sticks property to fix this issue but it has no effect on the output.
Here's my code to draw pie chart:
<script type="text/javascript">
$(document).ready(function(){
// Some data that is to be shown on the pie chart. It should be an array of numbers.
var data = [6.3, 2.1, 1.1, 3.2, 7.4, 10.5, 5.3, 27.4, 1.1, 4.2];
var labels = ['Data Loggers 6', 'Data Translation 2', 'Energy Loggers 1', 'Hobo 3', 'iButton 7', 'ICP 10', 'MCC 5', 'Monnit 26', 'Orchestrator 1', 'Sensors 4'];
for(var i = 0; i < data.length; i++)
{
labels[i] = labels[i] + ', ' + data[i] + '%';
}
var colors_arr = new Array('#00FFFF', '#7FFFD4', '#FFE4C4', '#0000FF', '#8A2BE2', '#A52A2A', '#7FFF00', '#FF7F50', '#B8860B', '#A9A9A9', '#8B008B', '#FF1493', '#228B22', '#DAA520', '#20B2AA', '#87CEFA', '#6B8E23', '#FF0000', '#FFFF00', '#F5DEB3');
var colors = new Array();
for(var i = 0; i < data.length; i++)
{
colors[i] = colors_arr[i];
}
// Create the Pie chart
var pie = new RGraph.Pie({
id: 'report_prospects_qty_products_canvas' ,
data: data,
options: {
labels: {
self: labels,
sticks: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
},
tooltips: {
self: labels,
//event: 'onmousemove',
},
shadow: false,
strokestyle: 'transparent',
title: {
self: 'Products',
bold: false,
y: 10
},
radius: 70,
colors: colors,
text: {
size: 8,
color: "red",
angle: 45
},
},
}).roundRobin();
$('#report_prospects_qty_products_wrapper').mouseout(function(){
// Hide the tooltip
RGraph.hideTooltip();
// Redraw the canvas so that any highlighting is gone
RGraph.redraw();
});
});
</script>
HTML
<!-- Put this where you want the chart to show up: -->
<div id="cvs_wrapper">
<!-- An example of using CSS to resize the canvas tag. -->
<canvas id="report_prospects_qty_products_canvas" width="600" height="250" style="width:100%;">[No canvas support]</canvas>
</div>
Output:
To fix labels clashing issue, I am using following option:
options: {
labels: {
self: labels,
sticks: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
},
According to RGraph docs:
labels.sticks Stipulates that sticks for the labels are shown. This
can also be an array of stick lengths - which may be useful if you're
experiencing the labels clashing. Default: false
FYI, I am using // version: 2015-05-24
Judging by the configuration snippet that you posted then I'm guessing that you might be using an older version. The current version (5.0 at this time) uses a far better way of arranging labels so there's no clashing (unless you have oodles of labels).
There's a demo page that shows this new method quite nicely here:
https://www.rgraph.net/demos/pie-basic.html
And the code for this is no different to what you might be used to:
labels = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ];
new RGraph.Pie({
id: 'cvs',
data: [20,1,1,1,1,1,1],
options: {
tooltips: labels,
labels: labels,
shadow: false,
colorsStroke: 'rgba(0,0,0,0)',
exploded: 0
}
}).roundRobin();

Resources