Highcharts. How to start areaspline chart from start y axis? - reactjs

I am new to highcharts so i might be missing something here.
Recently i was working on area chart and i was able to draw the chart and everything is perfect, But i have a requirement where i have area chart should start from x as 0. Is there any way to do this ? I have attached a screenshot and fiddle link.
Here is fiddle link: https://jsfiddle.net/shantanugade/9vwxm412/
Highcharts.chart('container', {
chart: {
type: 'area'
},
title: {
text: 'US and USSR nuclear stockpiles'
},
xAxis: {
allowDecimals: false,
labels: {
formatter: function () {
return this.value; // clean, unformatted number for year
}
},
accessibility: {
rangeDescription: 'Range: 1940 to 2017.'
}
},
yAxis: {
title: {
text: 'Nuclear weapon states'
},
labels: {
formatter: function () {
return this.value / 1000 + 'k';
}
}
},
tooltip: {
pointFormat: '{series.name} had stockpiled <b>{point.y:,.0f}</b><br/>warheads in {point.x}'
},
plotOptions: {
area: {
pointStart: 1940,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: true
}
}
}
}
},
series: [{
name: 'USA',
data: [
null, null, null, null, null, 6, 11, 32, 110, 235,
369, 640, 1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468,
20434, 24126, 27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342,
26662, 26956, 27912, 28999, 28965, 27826, 25579, 25722, 24826, 24605,
24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344, 23586, 22380,
21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950, 10871, 10824,
10577, 10527, 10475, 10421, 10358, 10295, 10104, 9914, 9620, 9326,
5113, 5113, 4954, 4804, 4761, 4717, 4368, 4018
]
}, {
name: 'USSR/Russia',
data: [ 1605, 2471, 3322, 4238, 5221, 6129, 7089, 8339, 9399, 10538,
5000, 2500, 500, 1200, 1500, 2000, 4260, 6600, 8690, 10600,
1605, 2471, 3322, 4238, 5221, 6129, 7089, 8339, 9399, 10538,
11643, 13092, 14478, 15915, 17385, 19055, 21205, 23044, 25393, 27935,
30062, 32049, 33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000,
37000, 35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000,
21000, 20000, 19000, 18000, 18000, 17000, 16000, 15537, 14162, 12787,
12600, 11400, 5500, 4512, 4502, 4502, 4500, 4500
]
}] })
As You can see in the image there is small gap.

You need to reduce xAxis.minPadding property:
xAxis: {
minPadding: 0,
...
}
Live demo: https://jsfiddle.net/BlackLabel/k2mzg0yq/
API Reference: https://api.highcharts.com/highcharts/xAxis.minPadding

Related

how to hide x axis bar on apex chart?

I'm used react-apexcharts to make this below graph, i need to show a minimal view of a graph so i hide both x, y axis, legends, grid and everything, but this bar at the bottom not hiding. i couldn't find the right option on the documentation! is there any way to hide this?
This is the current output i'm getting!
const ProductivityGraph = () => {
const series = [{
name: 'Series A',
data: [23, 24, 25, 15, 25, 28, 38, 46],
},
{
name: 'Series B',
data: [20, 29, 37, 36, 44, 45, 50, 58],
},
];
const options:any = {
chart: {
toolbar: { // Hamburger menu at top
show: false,
},
height: 350,
type: 'line',
zoom: {
enabled: false,
},
},
dataLabels: {
enabled: false,
},
stroke: {
curve: 'smooth',
width: 2,
},
title: {
text: undefined,
align: 'left',
},
grid: {
show: false,
},
legend: {
show: false,
},
xaxis: {
show: false,
labels: {
show: false,
},
},
yaxis: {
show: false,
labels: {
show: false,
},
axisBorder: {
show: false,
},
axisTicks: {
show: false,
},
crosshairs: {
show: false,
},
tooltip: {
enabled: false,
},
},
};
return (
<div>
<ReactApexChart options={options} series={series} type="line" width={250} />
</div>
);
};
In your options replace xaxis with below one
xaxis: {
show: false,
labels: {
show: false
},
axisBorder: {
show: false
},
axisTicks: {
show: false
}
},

Issue with chartjs linear gradient for the mixed bar chart in ReactJS is not calculated for each individual Bars

Our requirement is to render the bar chart as Expected Image. we are using chartJs library to render the chart. we are able to render the bar chart but for one of the bar we need to show
the background color as gradient. To achieve this we used the following below code snippet:
but it render as Rendered graph. Can you please help me out in rendering the chart as expected.
JSFiddleLink
const data = [{
type: "Sample 1",
data: [600, 400, 200, 800]
}, {
type: "Sampel 2",
data: [700, 300, 600, 600]
}, {
type: "Total",
data: [1300, 700, 800, 1400]
}];
const gradient = document.getElementById('myChart').getContext('2d').createLinearGradient(0, 250, 0, 0);
gradient.addColorStop(1, '#acd7fa')
gradient.addColorStop(0.4, '#FFFFFF')
new Chart('myChart', {
type: "bar",
data: {
labels: ["A", "B", "C", "D"],
datasets: [
{
label: data[0].type,
xAxisID: "x1",
data: data[0].data,
// fillColor: background_1,
// highlightFill: background_2,
backgroundColor: "rgb(54, 162, 235)" ,
// backgroundColor: background_1,
barPercentage: 1,
},
{
label: data[1].type,
xAxisID: "x1",
data: data[1].data,
backgroundColor:"rgb(255, 159, 64)",
barPercentage: 1,
},
{
label: data[2].type,
xAxisID: "x2",
data: data[2].data,
backgroundColor: gradient,
barPercentage: 1,
},
],
},
options: {
legend: {
labels: {
filter: item => item.text != 'Total'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
stepSize: 200
}
}],
xAxes: [{
id: 'x1'
},
{
id: 'x2',
display: false,
offset: true
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="150"></canvas>
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterLayout hook for creating different gradients for each value of the third dataset (the totals).
Please take a look at your amended code below and see how it works. You may also consult this StackBlitz that illustrates how it can be done with react-chartjs-2.
const data = [
{ type: "Sample 1", data: [600, 400, 200, 800] },
{ type: "Sampel 2", data: [700, 300, 600, 600] },
{ type: "Total", data: [1300, 700, 800, 1400] }
];
new Chart('myChart', {
type: "bar",
plugins: [{
afterLayout: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let yAxis = chart.scales["y-axis-0"];
let yBottom = yAxis.getPixelForValue(0);
let dataset = chart.data.datasets[2];
dataset.backgroundColor = dataset.data.map(v => {
let yTop = yAxis.getPixelForValue(v);
let gradient = ctx.createLinearGradient(0, yBottom, 0, yTop);
gradient.addColorStop(0.4, '#FFFFFF');
gradient.addColorStop(1, '#acd7fa');
return gradient;
});
ctx.restore();
}
}],
data: {
labels: ["A", "B", "C", "D"],
datasets: [{
label: data[0].type,
xAxisID: "x1",
data: data[0].data,
backgroundColor: "rgb(54, 162, 235)",
barPercentage: 1
},
{
label: data[1].type,
xAxisID: "x1",
data: data[1].data,
backgroundColor: "rgb(255, 159, 64)",
barPercentage: 1
},
{
label: data[2].type,
xAxisID: "x2",
data: data[2].data,
barPercentage: 1
}
]
},
options: {
legend: {
labels: {
filter: item => item.text != 'Total'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
stepSize: 200
}
}],
xAxes: [{
id: 'x1'
},
{
id: 'x2',
display: false,
offset: true
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="150"></canvas>

Chart is not rendering properly time axis

I have a lists of utc timestamps, ready to parse into ChartJS 2.9.3, the graph couldn't show the x-axis time and data is not showing.
Config
let chartConfig = {
type: "line",
data: {
labels: [],
datasets: [
{
pointRadius: 0,
data: [],
backgroundColor: ['rgba(255, 99, 132, 0.2)'],
borderColor: ['rgba(255,99,132,1)'],
borderWidth: 1
}
]
},
options: {
responsive: true,
animation: {
duration: 0
},
hover: {
animationDuration: 0
},
responsiveAnimationDuration: 0,
legend: {
display: false
},
scales: {
xAxes: [{
type: 'time',
ticks: {
source: "data",
autoSkip: true,
maxTicksLimit: 20
},
time: {
parser: 'HH:mm:ss',
tooltipFormat: 'HH:mm:ss',
unit: 'minute',
unitStepSize: 5,
displayFormats: {
'second': 'ss A',
'minute': 'hh:mm A',
'hour': 'HH:mm A'
}
}
}],
yAxes: [{
ticks: {min: 0, max: 150, stepSize: 10 }
}]
}
}
}
Labels (x-axis)
Generates through moment(timestamp).format("HH:mm:ss")
["22:02:30","22:03:00","22:03:30","22:4:00","22:05:00".,"22:07:00","22:10:00"]
Data (y-axis)
[60,78,89,100,120,45,55]
Problem
I took your code and everything works as expected as you can see below. The only thing I had to correct was removing a superfluous dot in the labels array.
new Chart('myChart', {
type: "line",
data: {
labels: ["22:02:30", "22:03:00", "22:03:30", "22:4:00", "22:05:00", "22:07:00", "22:10:00"],
datasets: [{
pointRadius: 0,
data: [60, 78, 89, 100, 120, 45, 55],
backgroundColor: ['rgba(255, 99, 132, 0.2)'],
borderColor: ['rgba(255,99,132,1)'],
borderWidth: 1
}]
},
options: {
responsive: true,
animation: {
duration: 0
},
hover: {
animationDuration: 0
},
responsiveAnimationDuration: 0,
legend: {
display: false
},
scales: {
xAxes: [{
type: 'time',
ticks: {
source: "data",
autoSkip: true,
maxTicksLimit: 20,
minRotation: 30
},
time: {
parser: 'HH:mm:ss',
tooltipFormat: 'HH:mm:ss',
unit: 'minute',
unitStepSize: 5,
displayFormats: {
'minute': 'hh:mm:ss A'
}
}
}],
yAxes: [{
ticks: {
min: 0,
max: 150,
stepSize: 10
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

How to skip labels of a line in multiline graph in chartjs?

I'm trying to create an multiline graph using chartjs.
On x-Axis I have dates and on y-Axis i have some amount in integers.
I have two lines, one of them for user's expenses and other for income.
For income I have data of only 2 dates but having difference of month. My second income point on the graph is not on the correct date, it comes on the next date of expenses.
My data looks like this :
[
{ date: '2020-02-24', type: 'income', amount: 900 },
{ date: '2020-03-20', type: 'expense', amount: 100 },
{ date: '2020-03-20', type: 'expense', amount: 830 },
{ date: '2020-03-21', type: 'expense', amount: 50 },
{ date: '2020-03-22', type: 'expense', amount: 560 },
{ date: '2020-03-24', type: 'expense', amount: 600 }
]
In labels dates of income are 2020-02-24 and 2020-03-24 and
rest of the dates are of expenses
Here is my dataset :
{
labels:[ "2020-02-24", "2020-03-20", "2020-03-20", "2020-03-21", "2020-03-22", "2020-03-24" ],
datasets: [
{
label: 'Expenses',
fill: false,
lineTension: 0.5,
backgroundColor: 'rgba(75,192,192,1)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 2,
data: [ 100, 830, 50, 560 ],
},
{
label: 'Income',
fill: false,
lineTension: 0.5,
backgroundColor: 'blue',
borderColor: 'red',
borderWidth: 2,
data: [ 900, 600 ],
}
]
};
You must not define data.labels, because they are considered for both datasets. Instead, you should define each data point individually using an object containing x and y properties.
data: [
{ x: '2020-02-24', y: 900 },
{ x: '2020-03-24', y: 600 }
]
In the following runnable code snippet, I build such data of individual datasets out of your base data array using filter() and map().
const data = [
{ date: '2020-02-24', type: 'income', amount: 900 },
{ date: '2020-03-15', type: 'expense', amount: 100 },
{ date: '2020-03-20', type: 'expense', amount: 830 },
{ date: '2020-03-25', type: 'expense', amount: 50 },
{ date: '2020-03-28', type: 'expense', amount: 560 },
{ date: '2020-03-24', type: 'income', amount: 600 }
];
var worldChart = new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
datasets: [
{
label: 'Expenses',
fill: false,
lineTension: 0.5,
backgroundColor: 'rgba(75,192,192,1)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 2,
data: data.filter(o => o.type == 'expense').map(o => ({ x: o.date, y: o.amount }))
},
{
label: 'Income',
fill: false,
lineTension: 0.5,
backgroundColor: 'blue',
borderColor: 'red',
borderWidth: 2,
data: data.filter(o => o.type == 'income').map(o => ({ x: o.date, y: o.amount }))
}
]
},
options: {
responsive: true,
title: {
display: false
},
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
tooltipFormat: 'MMM DD'
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="80"></canvas>
const options = {
responsive: true,
maintainAspectRatio: false,
scales: {
y: { title: { display: false, }, ticks: { color: "black", }, },
x: { ticks: { color: "black", autoSkip: true, }, grid: { display: false, } },
},
plugins: { legend: { display: false, }, title: { display: false, }, tooltip: { mode: "index", intersect: false, }, },
hover: { mode: "nearest", intersect: false, },
};
const data={{
labels: chartData?.labels,
datasets: [{ label: "Orders", type: "bar", barThickness: 12, borderRadius: 20, data: chartData?.data, backgroundColor: "#fb6340", },],
}}

Rendering HighCharts in AngularJS from Json Object

Learning AngularJS and HighCharts.
[Plunker Link][1]
I would like to understand how I can get the data from a JSON object and dynamically update the values on the x-axis and the bar chart value. The Y-axis values are constant.
Right now I have hard coded the values, I want the x-axis and bar chart values from the backend.
Here is what I have tried -
(function() {
'use strict';
angular.module('myModule', [])
// Directive for generic chart, pass in chart options
.directive('hcChart', function() {
return {
restrict: 'E',
template: '<div></div>',
scope: {
options: '='
},
link: function(scope, element) {
Highcharts.chart(element[0], scope.options);
}
};
})
.controller('MainCtrl', function($scope, $http) {
$scope.chartData = [];
$scope.totalCostList = [];
loadChartData();
function loadChartData() {
var httpRequest = $http({
method: 'GET',
url: './example.json'
}).then(function(response) {
console.log(response.data);
$scope.chartData = response.data;
console.log("length:" + $scope.chartData.activityResponse.length);
for (var i = 0; i < $scope.chartData.activityResponse.length; i++) {
$scope.totalCostList.push(parseInt($scope.chartData.activityResponse[i].totalCost));
}
console.log($scope.totalCostList);
});
}
//var chartData = $scope.totalCostList;
var yAxisLabels = [1, 5000, 10000, 15000, 20000];
var chartData = [
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000
];
var dateLine = Date.UTC(2015, 0, 1);
Highcharts.getOptions().colors[0] = {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#6EB7D8'],
[0.4, '#2989D8'],
[0.7, '#207cca'],
[1, '#1E5799']
]
};
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
//To give the chart a bounce effect
Math.easeOutBounce = function(pos) {
if ((pos) < (1 / 2.75)) {
return (7.5625 * pos * pos);
}
if (pos < (2 / 2.75)) {
return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
}
if (pos < (2.5 / 2.75)) {
return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
}
return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
};
$scope.chartOptions = {
chart: {
type: 'column',
margin: [70, 30, 30, 80]
},
exporting: {
enabled: false
},
credits: {
enabled: false
},
legend: {
enabled: false
},
title: {
text: 'Weekly Inventory at Cost',
style: {
color: '#333'
},
align: 'left',
x: 10,
y: 20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%b'
},
lineColor: '#333',
tickColor: '#333',
crosshair: true,
startOnTick: false,
endOnTick: false,
minPadding: 0,
maxPadding: 0,
tickmarkPlacement: 'on',
labels: {
align: 'left',
rotation: 0
}
},
yAxis: {
crosshair: true,
lineColor: '#333',
tickColor: '#333',
tickPositioner: function() {
return yAxisLabels;
},
labels: {
format: '{value:,.0f}'
},
title: {
enabled: false
},
lineWidth: 1,
tickWidth: 1,
id: 'cost',
gridLineWidth: 0,
min: 1
},
plotOptions: {
column: {
pointPadding: 0.1,
borderWidth: 0,
pointPlacement: 'between'
}
},
shadow: true,
series: [{
data: chartData,
pointStart: dateLine,
pointInterval: 7 * 24 * 3600 * 1000 // 7days
}]
};
});
})();
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<hc-chart options="chartOptions" style="width: 96%; height: 300px;">Placeholder for generic chart</hc-chart>
</body>
</html>
My example JSON -
{"message": "success",
"status": "OK",
"activityResponse": [{
"storeNo": "00208",
"wk": "1",
"year": "2016",
"totalCost": "349622.9"
},{
"storeNo": "00208",
"wk": "2",
"year": "2016",
"totalCost": "2000"
},
{
"storeNo": "00208",
"wk": "3",
"year": "2016",
"totalCost": "15000"
}]
}
Here is an approach to adding to the x-axis categories and updating the category values. Grab a reference to the chart's series when the chart is created.
var series = this.series[0];
Then, when there is an update to the data, make the following call.
series.setData(seriesDataSource, true, true, false);
I have adapted your Plunker to show an example of the chart with series records being added and updated.
https://embed.plnkr.co/SWGuRTyTM3AU6yhptYvM/

Resources