ApexCharts - Custom bar colour - apexcharts

Is it possible to customise the colour of each bar in a column chart ?
This is the kind of data I'm having using React:
const [data, setData] = useState([{
data: [{
x: 'Apple',
y: 54,
color: '#CCCCCC'
}, {
x: 'Orange',
y: 66,
color: '#FF0000'
}]
}]);
But the colours here is are not applied to the chart.
I've tried with the 'distributed' option set to true as well.
plotOptions: {
bar: {
distributed: true,
},
},

There are two ways to achieve this, you're very close to both of them.
1. Pass the color with the data
Very similar to what you've tried, but use fillColor as the key instead.
data: [{
x: 'Apple',
y: 54,
fillColor: '#CCCCCC'
}, {
x: 'Orange',
y: 66,
fillColor: '#FF0000'
}]
2. distributed option
For this to work, it needs to be nested inside the options object:
options: {
plotOptions: {
bar: {
distributed: true
}
}
},
If this doesn't work, it's worth making sure that there aren't any invalid attributes (e.g. color) somewhere that might be causing issues.
As I'm sure you've already discovered, there are some examples of various ways to use colors in a column chart in the ApexCharts docs.

Related

ApexCharts skipping X axis ticks

I would like to present a bar chart using Apex Charts.
The graphs shows some items, the more items the longer you can do some stuff. The items are presented in the Y axis. The X axis should represent months in a year, therefore I want it to be fixed between 0 and 12.
With the following options, it skips some numbers in the x axis:
var options = {
series: [{ data: [3,4,6,7,8.5] }],
chart: { type: 'bar', height: 250 },
plotOptions: {
bar: { borderRadius: 4, horizontal: true }
},
dataLabels: { enabled: false },
xaxis: {
categories: [2,3,5,6,7],
min: 0,
max: 12,
},
yaxis: {
labels: { formatter: function (val) { return val + ' items'; } },
},
title: {
text: 'Chart title', floating: true, align: 'center',
style: { color: '#444' }
}
};
If I omit the min/max in the xaxis, it works fine but the 12 months are not fixed as required.
In the example the 9 is skipped, but the actual bars are scalled correctly
I am loading the library using de direct script include:
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
Here you can find the official example/docs: https://apexcharts.com/javascript-chart-demos/bar-charts/basic/
Have I overlooked something? Or is it a bug?
Setting tickAmount to 12 seems to fix the problem, but I does not behave correctly with other numbers. (if I use 13 then it inserts two 6 tiks instead of inserting decimals)

Stacking area line charts with different x-values in data

We use the chart-js-react to build area charts in our service. Our chart will display logs information which is time-based data like, {x:"2022-06-27T21:00:00Z", y:25}.
Since the time could be a random value in each data point, so there are some issue when we want to display a few series with different X-values(different time), as shown in the image. We got overlapping and blank area when the X-value(timestamp) is missing in another series.
Update: checked this Issue: https://github.com/chartjs/Chart.js/issues/7695. I notice they did have some missing/ different X-value. but looks the x-value is not random. when I made the x-values mis-match. same issue: https://codepen.io/derrickwanglf/pen/RwMRMXM
TO Simply demonstrate our issue, I mock some data(real number as x-value) here.
https://codepen.io/derrickwanglf/pen/gOeMvEL
Do you know how can we stack the area chart even the x-values are random?
d0 = [{x:1, y:1}, {x:2, y:11},{x:3, y:1},{x:4, y:11},{x:5, y:10}, {x:6, y:8},{x:7, y:15},{x:8, y:2}]
d1= [{x:1, y:1}, {x:2, y:5}, {x:4, y:1}, {x:5, y:3}, {x:5.5, y:4},{x:7, y:5},{x:8, y:3}]
const ctx = document.getElementById("chart").getContext("2d");
const chart = new Chart(ctx, {
type: "line",
data: {
datasets: [
{
backgroundColor: "rgba(50,200,50,0.6)",
borderColor: "rgba(50,200,50,0.6)",
data: d0,
fill: "stack"
},
{
backgroundColor: "rgba(200,50,50,0.6)",
borderColor: "rgba(200,50,50,0.6)",
data: d1,
fill: "stack"
}
]
},
options: {
scales: {
x: {
type: "linear"
},
y: {
stacked: true,
}
},
elements: {
line: {
tension: 0.2
},
point: {
radius: 0
}
},
tooltips: {
mode: "nearest",
intersect: false,
axis: "x"
},
hover: {
mode: "nearest",
intersect: false,
axis: "x"
}
}
});

Chart.JS 2 automatic horizontal scroll upon changes on xAxis range not working anymore on Chart.JS 3?

I previously had a scatter graph in Chart.js 2 with the zoom plugin, in which I just had to add data and change the xAxis ticks' min/max to see a nice animated horizontal scroll from my old xAxis range to my new xAxis range.
For some reason I now use Chart.js 3.24 and the zoom plugin 1.1.1. Now the same graph with nearly the same options became quite ugly when animated:
newly added points e.g. at position (X,Y) have an animation going from (X,0) to (X,Y), instead of appearing directly at (X,Y).
when a point from a dataset is at the same position than a line from another dataset, they move at a different speed.
if many points and line are added, sometimes the lines are only shown after the "scrolling animation" ended.
sometimes a point appear at its correct final position before the "scrolling animation" even started.
The only solution I found was to disable animation when updating my graph, then use window.requestAnimationFrame to manually pan the graph myself with the zoom plugin.
Are you aware of a better/simpler recommended way to achieve this ?
Thanks in advance,
My old Chart.js options:
let zoom_options = {
pan: {
enabled: true,
mode: 'x',
rangeMin: { x: 0, y: null},
rangeMax: { x: null, y: null}
},
zoom: {
enabled: true,
drag: false,
mode: 'x',
rangeMin: { x: 0, y: null },
rangeMax: { x: null, y: null },
speed: 0.1
}
};
var ctx = graph.getContext('2d');
this._chartjs = new Chart(ctx, {
type: 'scatter',
data: {
datasets: []
},
options: {
legend: {
//display: false
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
}]
},
plugins: {
zoom: zoom_options // https://github.com/chartjs/chartjs-plugin-zoom
}
}
});
My old line options :
{
label: name,
showLine: false,
fill:false,
spanGaps: false, // I have some NaN values in my datasets.
backgroundColor: color.points_borders,
borderColor: color.line,
borderWidth:5,
pointRadius:5,
pointBorderWidth:2,
pointBorderColor: color.points_borders,
pointBackgroundColor: color.points,
data: []
}
My old update function:
this._chartjs.options.scales.xAxes[0].ticks.min = min;
this._chartjs.options.scales.xAxes[0].ticks.max = length;
this._chartjs.update();

Change color of a single point by clicking on it - Chart.JS

I'm building a scatter chart using Chart.JS(latest version), one of the behaviours I'm trying to implement is clicking on a single point and highlighting it by changing the background color of the selected point.
I've used the getElementsAtEvent method from the Chart.JS API in order to get the active element and change it's background. For a brief moment I can see it changing the color but it returns to its original color and all the other points now have the color I wanted to apply to the selected one... I tried various approaches to this, using the updated and render methods but with no desired result...
Here's the code inside the function that'll run onClick
function (evt, activeElements, chart) {
const selectedPoint = chart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
selectedPoint[0].element.options.backgroundColor = '#fa6400';
chart.update();
}
Here's a fiddle
https://jsfiddle.net/dc3x70yg/1/
Thanks in advance
You can define the option pointBackgroundColor on the dataset. When the user clicks on a point, you recreate pointBackgroundColor, but now use an array that contains the desired color for each point.
Please take a look at your amended code below and see how it works.
new Chart('myChart', {
type: 'scatter',
data: {
datasets: [{
label: '# of Votes',
data: [{ x: -10, y: 0 }, { x: 0, y: 10 }, { x: 10, y: 5 }, { x: 0.5, y: 5.5 }],
pointBackgroundColor: '#ddd',
pointRadius: 5,
}]
},
options: {
onClick: (event, elements, chart) => {
const dataset = chart.data.datasets[0];
dataset.pointBackgroundColor = dataset.data.map((v, i) => i == elements[0]?.index ? '#fa6400': '#ddd');
chart.update();
},
scales: {
y: {
beginAtZero: true
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>

Chart.js - scaleType='date' not working

Using Chart.js, I'm trying to get the x-axis (and toolips) to show a DATE, but all I can get are large integers appearing as the x-axis label. I've compared what the example in the documentation does and I don't see what it's doing that i'm not. Can anyone please help?
Here's the tiny example that I created showing it not working.
(btw - as a side issue, notice that if the color of the RED line is spelled Red rather than red, the line looks normal, but tooltips no longer work on that line)
https://plnkr.co/edit/CKUf4zFC1vhe3VNUF5Lf?p=preview
javascript for the above plunker example is below
----------------------------------------------------
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<canvas id="canvas"></canvas>
<script>
var chartData = {
datasets: [{
borderColor: 'Red',
label: 'Capital R in borderColor, tooltips dont work',
data: [{
x: new Date('2011-04-11T11:45:00'),
y: 25
}, {
x: new Date('2011-04-11T12:51:00'),
y: 28
}, {
x: new Date('2011-04-11T14:10:00'),
y: 22
}, {
x: new Date('2011-04-11T15:15:00'),
y: 18
}]
}, {
borderColor: 'green',
label: 'borderColor all lower case, tooltips now work',
data: [{
x: new Date('2011-04-11T11:45:00'),
y: 15
}, {
x: new Date('2011-04-11T12:51:00'),
y: 18
}, {
x: new Date('2011-04-11T14:10:00'),
y: 12
}, {
x: new Date('2011-04-11T15:15:00'),
y: 8
}]
}, ]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myScatterxx = Chart.Scatter(ctx, {
data: chartData,
scaleType: 'date',
options: { title: { display: true, text: "scaleType='date' isn't working", fontSize:36} },
});
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js">
</script>
</body>
</html>
First of all, since the documentation is messy, I'm not surprised you didn't get how to create a time-scale chart. The actual call is the following :
window.myScatterxx = Chart.Scatter(ctx, {
data: chartData,
options: {
title: {
display: true,
text: "it is now working",
fontSize: 36
},
scales: {
xAxes: [{
// This is the important part
type: "time",
}]
}
},
});
Now you have the correct syntax, you'd need to import the correct library as well. As I can see in the piece of code you gave, you imported Chart.min.js, but you need more since you know work with the time element.
You can either :
Import Moment.js (CDN link) and then Chart.min.js.
Import Chart.bundle.min.js, that contains both Moment and Chart libraries.
Finally, I also noticed in your code you had a problem displaying tooltips for the red dataset. It is because you defined its color as Red. Change it to red and tooltips will work again :
datasets: [{
borderColor: 'red',
label: 'Capital R in borderColor, tooltips now work',
data: [
// ...
]
}]
You can see all these fixes live in this jsFiddle, and here is the final result :