ChartJS: single bar of bar chart. I want a border around entire bar, including the max Y-value - javascript

I want to create a single bar using a bar chart. The setup is that the user can select different choices (representing the colors). In this example (codesandbox link below) I have a bar that has a max value of 90.000. The three chosen values are 20.000, 30.000 and 15.000, totaling 65.000.
Now, my goal is to have a border around this entire bar, not just the colors. In the image below this is represented with the red border. Currently I do this by putting a container element around my canvas element, but I would like to do this in the canvas itself, without using a container element. Someone has an idea on how to do this?
Codesandbox link

You need to define different dataset properties such as borderSkipped, borderRadius, borderWidth to achieve what you're looking for.
Don't know why but I also had to define the data of the dataset at the bottom as a floating bar in order to see the rounded border.
data: [[0, 20000]]
Please take a look at the runnable code below and see how it could work.
new Chart('chart', {
type: 'bar',
data: {
labels: [''],
datasets: [{
label: "currentAmount",
data: [[0, 20000]],
backgroundColor: "#bbb",
borderColor: "#f00",
borderWidth: 2,
borderSkipped: 'top',
borderRadius: 30,
barPercentage: 0.5
},
{
label: "amount 1",
data: [30000],
backgroundColor: "orange",
borderColor: "#f00",
borderWidth: { left: 2, right: 2 },
barPercentage: 0.5
},
{
label: "amount 2",
data: [15000],
backgroundColor: "green",
borderColor: "#f00",
borderWidth: { left: 2, right: 2 },
barPercentage: 0.5
},
{
label: "remaining",
data: [25000],
backgroundColor: "#fff",
borderColor: "#f00",
borderWidth: 2,
borderSkipped: 'bottom',
borderRadius: 30,
barPercentage: 0.5
},
]
},
options: {
plugins: {
legend: {
display: false
},
tooltip: {
displayColors: false
}
},
scales: {
y: {
display: false,
stacked: true,
beginsAtZero: true
},
x: {
display: false,
stacked: true
}
}
}
});
canvas {
max-width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="chart"></canvas>

Related

How to add a title in Doughnut chart chart.js React

I want to add a Title for the Doughnut chart in my React app but for some reason it doesn't work. I have this code:
const chartData = {
labels: [],
datasets: [{
data: [],
backgroundColor: [
Colors.primary,
Colors.secondary,
Colors.danger,
Colors.warning
],
hoverBackgroundColor: [
'rgb(143, 0, 180, 0.3)',
'rgb(0, 196, 204, 0.3)',
'rgb(206, 0, 0, 0.3)',
'rgb(255, 179, 0, 0.3)'
],
hoverOffset: 10
}]
};
const options = {
responsive: true,
legend: {
display: false,
position: 'right',
},
title: {
display: true,
fontSize: 20,
text: 'Tickets'
}
}
<Doughnut
data = { chartData }
options = { options }
/>
What could have gone wrong here? I also want to place the labels on the right side of the chart, but it doesn't work as well. Below is the output.
Since Chart.js version 3 title, subtitle, legend and tooltip are plugins and their options must be defined in plugins node.
As far as I have seen, react-chartjs-2 is working with Chartjs version >= 3.
const options = {
responsive: true,
plugins: {
legend: {
display: false,
position: 'right',
},
title: {
display: true,
fontSize: 20, // <--- this is not a managed option since CHART.JS 3
text: 'Tickets'
}
}
}

How to get radar chart coordinates using getValueForDistanceFromCenter with Chart.js?

I am experimenting with Chart.js to build radar charts. I mastered the basics (see basic chart below), but I would like to use the x y coordinates of the graph to place texts directly on the canvas.
After some digging, I found out that it is not possible to use getValueForPixel or getPixelForTick in a radar chart. See this github issue. In the connecting thread, a new method getValueForDistanceFromCenter is introduced.
As I understand it, it would be possible to calculate the distance from the center with this method, and use it to get coordinates. I searched the Chart.js documentation and other sites, but cannot find any code examples or information on how to implement this.
Can somebody point me in the right direction how to implement the method in the code?
var data = {
labels: ["Ball Skills", "Shooting", "Physical"],
datasets: [{
label: [`ikke`, `jij`],
backgroundColor: "rgba(38,120,255,0.2)",
borderColor: "rgba(38,120,255, 1)",
data: [90, 90, 90]
}]
};
var options = {
responsive: true,
tooltips: false,
title: {
text: 'Basic example',
display: true,
position: `bottom`,
},
scale: {
angleLines: {
display: true
},
ticks: {
suggestedMin: 0,
suggestedMax: 100,
stepSize: 25,
maxTicksLimit: 11,
display: false,
}
},
legend: {
labels: {
padding: 10,
fontSize: 14,
lineHeight: 30,
},
},
};
var myChart = new Chart(document.getElementById("chart"), {
type: 'radar',
data: data,
options: options
});
The radialLinear scale (in version 2.9.4 that I have seen your are using version 2) there is the method getValueForDistanceFromCenter(value) to get the distance from center but there is another method getPointPositionForValue(index, value) which can provide you the point at a specif index of your data.
To use them and to draw what you want on chart using those points, you need to implement a plugin.
In the below snippet, I'm drawing a rect between the points at a specific value.
const ctx = document.getElementById("myChart");
const data = {
labels: ["Ball Skills", "Shooting", "Physical"],
datasets: [{
label: [`ikke`, `jij`],
backgroundColor: "rgba(38,120,255,0.2)",
borderColor: "rgba(38,120,255, 1)",
data: [50, 50, 50]
}]
};
const options = {
responsive: true,
tooltips: false,
title: {
text: 'Basic example',
display: true,
position: `bottom`,
},
scale: {
angleLines: {
display: true
},
ticks: {
suggestedMin: 0,
suggestedMax: 100,
stepSize: 25,
maxTicksLimit: 11,
display: false,
}
},
legend: {
labels: {
padding: 10,
fontSize: 14,
lineHeight: 30,
},
},
};
const plugin = {
id: 'getDistance',
afterDraw(chart) {
const c = chart.ctx;
const rScale = chart.scale;
c.save();
chart.data.datasets[0].data.forEach(function(item, index) {
const point = rScale.getPointPositionForValue(0.5 + index, 50);
c.beginPath();
c.fillStyle = 'red';
c.fillRect(point.x - 5, point.y - 5, 10, 10);
c.fill();
});
c.restore();
}
};
const myChart = new Chart(ctx, {
type: 'radar',
plugins: [plugin],
data: data,
options: options
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
</body>
</html>

How do I remove cartesian axes from chart js?

I am trying to personalize a chart.js. But I can not find how to remove (or hide) the X and Y axes.
I am also interested in not showing data on hover and I would like not to show the reference on the top. I am just starting with chart.js and I only need to do a few graphs.
Thank you :)
This is the graph I currently have
datasets: {
label: "I need help plz",
backgroundColor: gradient,
fill: true,
borderColor: "rgb(0, 50, 100)",
borderWidth: 0.001,
tension: 0.4,
radius: 0,
data: dataset,
},
For removing the references on the top this post was useful Chart.js v2 hide dataset labels
As described in the documentation (https://www.chartjs.org/docs/master/axes/#common-options-to-all-axes) you can set in the options of the scale the display to true or false or 'auto' where auto hides the scale if no dataset is visable that is linked to that axis.
For not showing data on hover you can set the tooltip to enabled: false
Example (y auto display and no x axis):
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1,
backgroundColor: 'red'
}, ]
},
options: {
plugins: {
tooltip: {
enabled: false
}
},
scales: {
y: {
display: 'auto'
},
x: {
display: false
}
}
}
}
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.3.2/chart.js"></script>
</body>

How to maintain chartjs / ng2-charts gradient on window resize?

I had applied some gradient rule to my chartjs chart. And it looks great as you can see on the below
However, when the browser window is resized (i.e. width of window is smaller), the gradient is ruined (bottom blue colors disappeared). Screenshot:
I want to maintain the graph's gradient with all values and fit the different widths (responsive). Is there any way to do that? Here is what I had tried but didn't work:
.TS File
ngAfterViewInit() {
const ctx = (<HTMLCanvasElement>this.myChart.nativeElement).getContext('2d');
const purple_orange_gradient = ctx.createLinearGradient(0, 200, 0, 20);
purple_orange_gradient.addColorStop(0.1, "#000279");
purple_orange_gradient.addColorStop(0.2, "#0000F2");
purple_orange_gradient.addColorStop(0.3, "#0362FD");
purple_orange_gradient.addColorStop(0.4, "#04D3FD");
purple_orange_gradient.addColorStop(0.5, "#45FFB7");
purple_orange_gradient.addColorStop(0.6, "#B7FF46");
purple_orange_gradient.addColorStop(0.7, "#FFD401");
purple_orange_gradient.addColorStop(0.8, "#FE6500");
purple_orange_gradient.addColorStop(0.9, "#F30004");
purple_orange_gradient.addColorStop(1, "#7E0100");
const bar_chart = new Chart(ctx, {
type: "horizontalBar",
data: {
labels: []=this.histogramLabels.reverse(),
datasets: [{
borderColor: purple_orange_gradient,
pointBorderColor: purple_orange_gradient,
pointBackgroundColor: purple_orange_gradient,
pointHoverBackgroundColor: purple_orange_gradient,
pointHoverBorderColor: purple_orange_gradient,
pointBorderWidth: 10,
pointHoverRadius: 10,
pointHoverBorderWidth: 1,
pointRadius: 3,
fill: true,
backgroundColor: purple_orange_gradient,
borderWidth: 4,
data: []=this.histogramGraphData
}]
},
options: {
legend: {
display:false,
position: "bottom"
},
scales: {
yAxes: [{
ticks: {
display: false,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 1,
padding: 20,
},
gridLines: {
drawTicks: false,
display: false
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
beginAtZero: true,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold"
}
}]
}
}
}
)
}
.HTML
<div class="row my-2">
<div class="col-md-6">
<canvas id=”myChart” #myChart height="130"></canvas>
</div>
</div>
HTML Canvas' createLinearGradient() depends on the y axis coordinates that you pass in as argument. You had passed in a static 200 every time (i.e. ctx.createLinearGradient(0, 200, 0, 20);).
That's why the gradient's steps remains the same everytime. For the gradient to update, you have to recalculate the height of the <canvas> element on window resize and pass it in to createLinearGradient() again.
You can accomplish this by:
Separating the block where you create the gradient into a separate function. eleHeight retrieves the height of the canvas element.
generateGradient(){
let eleHeight = this.myChart.nativeElement.offsetHeight;
// console.log(eleHeight)
let purple_orange_gradient: CanvasGradient = this.myChart.nativeElement.getContext('2d').createLinearGradient(0, eleHeight, 0, 20);
purple_orange_gradient.addColorStop(0.1, "#000279");
purple_orange_gradient.addColorStop(0.2, "#0000F2");
purple_orange_gradient.addColorStop(0.3, "#0362FD");
purple_orange_gradient.addColorStop(0.4, "#04D3FD");
purple_orange_gradient.addColorStop(0.5, "#45FFB7");
purple_orange_gradient.addColorStop(0.6, "#B7FF46");
purple_orange_gradient.addColorStop(0.7, "#FFD401");
purple_orange_gradient.addColorStop(0.8, "#FE6500");
purple_orange_gradient.addColorStop(0.9, "#F30004");
purple_orange_gradient.addColorStop(1, "#7E0100");
return purple_orange_gradient;
}
Add a onresize event handler to your containing <div> and generate the gradient again. You also need to programatically update the chart every time you make a change to re-render it.
<div style="display: block; max-height: 100%" (window:resize)="onResize($event)" >
...
</div>
onResize(event?){
// console.log("onResize");
this.barChartData.forEach((d, i) => {
d.backgroundColor = this.generateGradient();
})
this.chart.chart.update(); //update the chart to re-render it
}
Update the barchartData's properties (that uses gradient) in ngAfterViewInit. We need to do this here because we only want the height of the <canvas> element with data populated. Without data populated, the element is much smaller.
ngAfterViewInit(){
this.barChartData.forEach((d, i) => {
d.backgroundColor = this.generateGradient();
});
this.chart.chart.update(); //update the chart to re-render it
}
Have a look at this Stackblitz example⚡⚡ I have created.
You have to change the gradient whenever your canvas is resizing. Took me a while to figure out a good structure to minimize lines of code and optimize performance. This is the best I could achieve.
There are exeptions when the chart.js onResize() fires though but I couldn't solve this issue completly bulletproof. But for simple resizes it should work.
Complete code (same code in JSBin with live preview):
let sData = {}
sData.labels = []
sData.data = []
const count = 50
for (let x = 0; x < count; x++) {
sData.data.push(Math.floor(Math.random()*100))
sData.labels.push(x)
}
const canvas = document.getElementById('chart')
const ctx = canvas.getContext("2d")
let purple_orange_gradient
function updateGradient() {
let bottom = bar_chart.chartArea.bottom
let top = bar_chart.chartArea.top
purple_orange_gradient = ctx.createLinearGradient(0, bottom+top, 0, top)
purple_orange_gradient.addColorStop(0.1, "#000279")
purple_orange_gradient.addColorStop(0.2, "#0000F2")
purple_orange_gradient.addColorStop(0.3, "#0362FD")
purple_orange_gradient.addColorStop(0.4, "#04D3FD")
purple_orange_gradient.addColorStop(0.5, "#45FFB7")
purple_orange_gradient.addColorStop(0.6, "#B7FF46")
purple_orange_gradient.addColorStop(0.7, "#FFD401")
purple_orange_gradient.addColorStop(0.8, "#FE6500")
purple_orange_gradient.addColorStop(0.9, "#F30004")
purple_orange_gradient.addColorStop(1.0, "#7E0100")
return purple_orange_gradient
}
const bar_chart = new Chart(ctx, {
type: "horizontalBar",
data: {
labels: sData.labels,
datasets: [{
borderColor: purple_orange_gradient,
pointBorderColor: purple_orange_gradient,
pointBackgroundColor: purple_orange_gradient,
pointHoverBackgroundColor: purple_orange_gradient,
pointHoverBorderColor: purple_orange_gradient,
pointBorderWidth: 10,
pointHoverRadius: 10,
pointHoverBorderWidth: 1,
pointRadius: 3,
fill: true,
backgroundColor: purple_orange_gradient,
borderWidth: 4,
data: sData.data
}]
},
options: {
legend: {
display: false,
position: "bottom"
},
scales: {
yAxes: [{
ticks: {
display: false,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 1,
padding: 20,
},
gridLines: {
drawTicks: false,
display: false
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
beginAtZero: true,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold"
}
}]
},
onResize: function(chart, size) {
// onResize gradient change
changeGradient()
}
}
});
// Initial gradient change
changeGradient()
function changeGradient() {
let newGradient = updateGradient()
bar_chart.data.datasets[0].borderColor = newGradient
bar_chart.data.datasets[0].pointBorderColor = newGradient
bar_chart.data.datasets[0].pointBackgroundColor = newGradient
bar_chart.data.datasets[0].pointHoverBackgroundColor = newGradient
bar_chart.data.datasets[0].pointHoverBorderColor = newGradient
bar_chart.data.datasets[0].backgroundColor = newGradient
bar_chart.update()
}

FlotChart - how to assign a color to a particular series in a linechart?

I use a flotcharts JS linechart to display the value of different stock tradepositions. The user can show/hide each trade on the chart via a checkbox above the chart.
By default, linecharts use default or predefined colors from me in the order the series are created. So the first line gets color1, the second color 2 etc.
This is not very good for this situation, because when the user hides the line for trade one, the previously trade two becomes the new "first line" and also changes its color from color 2 to color 1.
As the data represented by the line are still the same this behaviour is very irritating.
To solve this I would like to assign a color to a series by it's name, id or similar rather than by the order it was created on the chart, as this identifier stays the same even after adding/removing other lines from the chart.
How can I do this?
Currently I use a code like this to set the color for the first, second etc line.
var datatoprint=[];
for(var key in arrTradeSymbols){
if (arrTradeSymbols[key].visible==true){
datatoprint.push(arrTradeSymbols[key].data);
jQuery("#symb_"+arrTradeSymbols[key].tradeid).prop("checked",true);
}
}
var plot = $.plot(jQuery("#kt_flotcharts_pl"), datatoprint, {
legend: {
position: "nw",
},
series: {
lines: {
show: true,
lineWidth: 2,
fill: false,
},
points: {
show: true,
radius: 3,
lineWidth: 1,
color: '#00ff00'
},
shadowSize: 2
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#eee",
borderColor: "#eee",
borderWidth: 1
},
colors: ['#0083d0', '#1dc9b7'],
xaxis: {
mode: "time",
tickSize: [5, "day"],
tickLength: 0,
tickColor: "#eee",
},
yaxis: {
ticks: 11,
tickDecimals: 0,
tickColor: "#eee",
}
});
That's easy: just supply an array of objects with the color along with the data instead of only the data as an array.
Example snippet:
var arrTradeSymbols = {
trade1: {
color: "red",
data: [
[1, 3],
[2, 4],
[3.5, 3.14]
]
},
trade2: {
color: "green",
data: [
[1, 4],
[2, 11.01],
[3.5, 5.14]
]
}
};
function run() {
var datatoprint = [];
for (var key in arrTradeSymbols) {
if ($("#" + key).is(":checked")) {
datatoprint.push(arrTradeSymbols[key]);
}
}
$.plot($("#kt_flotcharts_pl"), datatoprint, {
legend: {
position: "nw",
},
series: {
lines: {
show: true,
lineWidth: 2,
fill: false
},
points: {
show: true,
radius: 3,
lineWidth: 1
},
shadowSize: 2
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#eee",
borderColor: "#eee",
borderWidth: 1
},
xaxis: {
ticks: 5
},
yaxis: {
ticks: 11,
tickDecimals: 0,
tickColor: "#eee",
}
});
}
run();
$("input").on("input", run);
#kt_flotcharts_pl {
width: 400px;
height: 200px;
border: 1px solid black;
}
label {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.min.js"></script>
<label><input type="checkbox" id="trade1" checked> Red</label>
<label><input type="checkbox" id="trade2" checked> Green</label>
<div id="kt_flotcharts_pl"></div>

Categories