Resizing vue-chartjs height while keeping it responsive - vue.js

Need help with chart js
ACTUALLY, I'M USING VUE-CHARTJS BUT IT'S JUST A WRAPPER
in the line chart on the left side, the number is increasing by 5(0, 5, 10, 15, etc) I want it to increase by 10 and also decrease the height of the chart so the aspect ratio is something like 16/9
also is it possible to make the left number say 5k+, 10k+, 15k+ instead of just 5, 10, 15
here's my code for the chart
<script>
import { Line } from 'vue-chartjs'
export default {
extends: Line,
data: () => ({
chartdata: {
labels: ['January', 'February', 'March', 'April', 'May','Jun'],
datasets: [
{
data: [12, 20, 27, 22, 14, 10],
borderColor: "#135193",
pointBackgroundColor: "#135193",
pointBorderColor: "#135193",
backgroundColor: 'rgba(255, 255, 255, 0)'
},
{
data: [3, 12, 17, 20, 30, 40],
borderColor: "#FF8811",
pointBackgroundColor: "#FF8811",
pointBorderColor: "#FF8811",
backgroundColor: 'rgba(255, 255, 255, 0)'
}
]
},
options: {
responsive: true,
legend: {
display: false
}
}
}),
mounted () {
this.renderChart(this.chartdata, this.options)
}
}
</script>

Yes, you can just use CSS to set the dimensions of the canvas and set maintainAspectRatio to false in the options, for the ticks you can use the tick callback:
const labels = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"];
const options = {
type: 'line',
data: {
labels,
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'red',
backgroundColor: 'pink'
}]
},
options: {
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
callback: (val) => (`${val}K`)
}
}]
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
canvas {
max-height: 180px;
max-width: 320px;
}
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Okay it turns out its as simple as wrapping the chart with a container and set height of that container as needed

Related

Remove empty space around a barchart with no axes showing in Chartjs

Fairly straightforward, but I have a single bar on a barchart that I want to show by itself. I've hidden the axes and their ticks, but there is still all of that space there on the left and top//bottom of chart from the axes and the legend I am presuming.
Is there a way to remove this space without just putting negative margins on the element?
I've tried working with negative padding, but that doesn't work on the top and bottom of the chart.
I made a quick CodeSandbox to show my actual component
Any tips would be greatly appreciated!
Cheers!
Horizontal Stacked Bar Chart
<template>
<div style="width: 100%; height: 100%">
<canvas :id="id" width="100%" height="100%"></canvas>
</div>
</template>
<script>
import { defineComponent, onMounted } from "vue"
import Chart from "chart.js/auto"
import ChartDataLabels from "chartjs-plugin-datalabels"
export default defineComponent({
props: {
kind: {
/**
* #example: 'single', 'stacked'
*/
type: String,
default: "stacked",
},
color: {
type: String,
default: "rgba(255, 99, 132, 1)",
},
labels: {
type: Array,
default: () => ["S1", "S2", "S4", "S6"],
},
datasets: {
type: Array,
default: () => [
{
label: "va_value",
data: [80, 10, 60, 50],
backgroundColor: "#11DCB5",
borderColor: "transparent",
barThickness: 20,
minBarLength: 4,
// This is here to show SOMETHING even if the value is 0
},
{
label: "nva_value",
data: [20, 0, 40, 0],
backgroundColor: "#CA2F4B",
borderColor: "transparent",
barThickness: 20,
minBarLength: 4,
},
],
},
},
setup(props, context) {
const id = Math.random().toString()
onMounted(() => {
Chart.register(ChartDataLabels)
const ctx = document.getElementById(id)
const myChart = new Chart(ctx, {
type: "bar",
data: {
labels: props.labels,
datasets: props.datasets,
},
options: {
layout: {
padding: {
left: -20,
bottom: -20,
top: -20
}
},
plugins: {
legend: {
display: false,
},
datalabels: {
formatter: function (value) {
return props.kind === "stacked" ? `${value}s` : `${value}%`
},
color: "#fff",
anchor: "center",
align: "center",font: {
weight: "bold",
},
},
},
responsive: true,
maintainAspectRatio: false,
indexAxis: "y",
scales: {
y: {
beginAtZero: true,
stacked: true,
ticks: {
color: "#fff",
},
grid: {
drawBorder: false,
display: false,
},
},
x: {
display: props.kind === "stacked" ? true : false,
beginAtZero: true,
stacked: true,
ticks: {
color: "#fff",
},
grid: {
drawBorder: false,
display: false,
},
title: {
display: true,
text: props.kind === "stacked" ? "Step Time (s)" : "",
color: "#fff",
},
},
},
},
})
myChart
})
return { id }
},
})
</script>
<style lang=""></style>
This is because you set barThickness to 20 in your datasets. If you remove this it will show as you want:
https://codesandbox.io/s/modest-wave-60xui0

How to show small values in a chart.js pie chart

I am having trouble displaying small values in my chart.js chart. My issue is very similar to a question asked here:
How to show small values in Flot Pie chart
Does anyone know if there is a workaround in chart.js?
You can use chartjs-plugin-datalabels and define a dataset with same data but weight: 0 for displaying small values outside of the chart.
{
data: data,
weight: 0,
borderWidth: 20,
datalabels: {
formatter: v => v < 5 ? v : ''
}
}
Then also add a datalabels.formatter to the original dataset and make sure, it returns an empty string for small values.
datalabels: {
textAlign: 'center',
formatter: v => v < 5 ? '' : v
}
Please take a look at the runnable code below and see how it works.
const data = [48, 56, 3, 1, 44];
Chart.register(ChartDataLabels);
new Chart('myChart', {
type: 'pie',
data: {
labels: ['red', 'blue', 'green', 'purple', 'gray'],
datasets: [{
data: data,
weight: 0,
borderWidth: 20,
datalabels: {
formatter: v => v < 5 ? v : ''
}
},
{
label: 'My Dataset',
data: data,
backgroundColor: ['rgba(255, 0, 0, 0.2)', 'rgba(0, 0, 255, 0.2)', 'rgba(0, 255, 0, 0.2)', 'rgba(145, 90, 185, 0.2)', 'rgba(124, 124, 124, 0.2)'],
datalabels: {
textAlign: 'center',
formatter: v => v < 5 ? '' : v
}
}
]
},
options: {
responsive: false,
plugins: {
legend: {
display: false
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2"></script>
<canvas id="myChart" height="300"></canvas>

How to put vertical dashed gridlines on Highcharts heatmap

I'm plotting a HighCharts heatmap of a wafer with around 50~70k points (it's like a CPU/processor silicon wafer). I need to put horizontal and vertical gridlines visible on the map, so that our engineers can easily figure out what's going on with the actual unit.
I have two concerns:
Horizontal gridlines are already OK, but the vertical gridlines are not drawn or visible. I thought, I just need to set gridZIndex=4. Kindly see image below - it should be drawn based on xAxis.tickPositions values (similar to yAxis)
I put some color options I found, but none of them could change the grid's color.
So far this is my code:
var option = {
chart: {
type: 'heatmap',
zoomType: 'xy',
},
boost: {
useGPUTranslations: true
},
title: {
text: chrt_title,
align: 'left',
x: 0,
style: {
fontSize: '12px',
}
},
exporting: {
buttons: {
contextButton: {
menuItems: [
'viewFullscreen', 'downloadPNG', 'downloadXLS'
]
}
},
enable: true,
},
xAxis: {
title: {
text: null
},
labels: {
enabled: false,
},
tickPositions: [1, 19, 43, 67, 91, 115, 139, 163, 183],
gridZIndex: 4, // DOESN'T WORK
gridLineDashStyle: 'Dash',
gridLineWidth: 1, // DOESN'T WORK
lineColor: 'red',
minorTickColor: 'red',
tickColor: 'red'
},
yAxis: {
title: {
text: null
},
reversed: true,
labels: {
enabled: false,
},
tickPositions: [1, 82, 116, 174, 272, 370, 428, 462, 544]
gridZIndex: 4, // ONLY PUT THIS AND WORKS ALREADY
gridLineDashStyle: 'Dash', // THIS WORKS TOO (Dot,Solid,etc)
lineColor: 'red',
minorTickColor: 'red',
tickColor: 'red'
},
colorAxis: {
stops: colrstops,
min: minval,
max: maxval,
startOnTick: true,
endOnTick: true,
labels: {
format: '{value}',
style: {
fontSize: '8px',
fontFamily: 'Verdana, sans-serif'
}
}
},
series: [{
boostThreshold: 100,
borderWidth: 0,
nullColor: '#ffffff',
tooltip: {
headerFormat: chrt_title + '<br/>',
pointFormat: 'RB{point.y} SL{point.x} <b>{point.value}</b>'
},
turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
data: data
}]
}
As you can see, both xAxis and yAxis have gridZIndex = 4, gridLineDashStyle = 'Dash', but only the yAxis that gives the horizontal gridlines, no luck for xAxis (assuming this is where need to set the vertical gridlines) :(
the only similar question i found reg vertical gridlines is this one:
Highcharts: xAxis with vertical gridlines
but I tried to put the gridLineWidth=1, still nothin's happening T-T please help. thanks very much.
Update:
I temporarily replaced my option{} based on #ppotaczek sample but vertical gridlines still did not appeared.
Then I played with my own option{}, tried to add min and max in xAxis, and tried to temporarily removed my dynamic data and use #ppotaczek sample, the layout remains the same (no vertical gridlines)..
Also thought it has something to do with the version i'm using..? it's 9.0.1 - so I tried to update to latest 9.1.1, but also have same result.
var option = {
chart: {
type: 'heatmap',
},
xAxis: {
tickPositions: [1, 19, 43, 67, 91, 115, 139, 163, 183],
min: 1,
max: 183,
gridZIndex: 4, // DOESN'T WORK
gridLineDashStyle: 'Dash',
gridLineWidth: 1, // DOESN'T WORK
lineColor: 'red',
minorTickColor: 'red',
tickColor: 'red'
},
yAxis: {
title: {
text: null
},
reversed: true,
labels: {
enabled: false,
},
tickPositions: [1, 82, 116, 174, 272, 370, 428, 462, 544],
gridLineDashStyle: 'Dash', // THIS WORKS TOO (Dot,Solid,etc)
lineColor: 'red',
minorTickColor: 'red',
tickColor: 'red',
},
colorAxis: {},
series: [{
data: [
[10, 0, 1],
[20, 1, 5],
[30, 1, 5],
],
}]
}

Increase gap between line-chart and legend ChartJS

I've been researching for hours trying to figure out this issue. I use ChartJS and trying to build line chart. It seems i have no gap between my chart and its legend, and need to add more space between them.
It should be like this:
But i got this (see my code snippet)
Here's my code:
new Chart(document.getElementById("line-chart"), {
type: "line",
data: {
labels: ["Label1", "Label2", "Label3", "Label4"],
datasets: [
{
label: "A",
fill: false,
data: [10, 30, 60, 100],
borderWidth: 1,
backgroundColor: "red",
borderColor: "red",
},
{
label: "B",
fill: false,
data: [28, 80, 60, 60],
borderWidth: 1,
backgroundColor: "green",
borderColor: "green",
},
],
},
options: {
legend: {
align: "start",
position: "right",
labels: {
usePointStyle: true,
fontSize: 10,
},
},
elements: {
line: {
tension: 0,
},
},
responsive: true,
maintainAspectRatio: false,
},
});
canvas {
height: 35vh !important;
width: 90%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<head></head>
<body>
<canvas id="line-chart"></canvas>
</body>
Depending on where the legend is placed there are some quick fix options available. See this question
For your case and, more often than not, I would recommend generating your own html legend which will give you full control.
You can set this up in the options:
options: {
legend: {
display:false, //turn default legend off
},
legendCallback : legendBuilder, //link to your custom function returning html string
}
Define where your legend will go in the html:
<div id="chart-container">
<canvas id="line-chart"></canvas>
<div id="chart-legend"></div>
</div>
Then generate your legend:
var myLegend = document.getElementById("chart-legend");
myLegend.innerHTML = myChart.generateLegend();
working example

Trying to get _index of clicked bar in ChartJS

I have a bar chart in vue-charts where when clicked I want to display the background data in a table. This is the render
startPie: function(canvas, type){
let chart = new Chart(canvas, {
type: type,
data: {
labels: this.labels,
datasets: this.chart_data
},
options: {
responsive: true,
animation:{ animateScale:true },
title: { display: false },
legend: { display: false },
scales: {
yAxes: [{
gridLines: {
color: "#989898"
},
ticks: {
fontColor: "#989898",
fontSize: 16,
beginAtZero: true,
callback: function(value) {
let ranges = [
{ divider: 1e6, suffix: 'M' },
{ divider: 1e3, suffix: 'k' }
];
function formatNumber(n) {
for (let i = 0; i < ranges.length; i++) {
if (n >= ranges[i].divider) {
return (n / ranges[i].divider).toString() + ranges[i].suffix;
}
}
return n;
}
return '$' + formatNumber(value);
}
}
}],
xAxes: [{
ticks: {
fontColor: "#989898",
fontSize: 12
}
}]
},
plugins: {
datalabels: {
anchor: 'center',
font: {
size: 16,
weight: 'bold'
},
formatter: function(value, context) {
return '$' + Number(value).toLocaleString();
},
color: 'white'
}
},
'onClick':(evt, item) => {
console.log('CLICK', item[0]);
}
}
})
}
In the onClick Event in the console I can see the index
CLICK ChartElement {_chart: Chart, _datasetIndex: 0, _index: 4,
hidden: false, _xScale: ChartElement, …}
I can't access it though without an error. I have tried
item[0]._index, item[0]['_index'], item[0]['ChartElement']._index, item[0]['ChartElement']['_index']
Any help is appreciated.
Unfortunately, the onClick event handler is poorly documented. You could try to define the data in a separate variable outside of the chart configuration.
const data = [55, 68, 82, 48, 75, 45, 67];
Then, you can define the onClick event handler as follows:
options: {
...
onClick: (event, item) => {
const idx = chart.getElementAtEvent(event)[0]._index;
console.log(data[idx]);
}
}
const labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"];
const data = [55, 68, 82, 48, 75, 45, 67];
let chart = new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: "My First Dataset",
data: data,
backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
borderWidth: 1
}]
},
options: {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
color: "#989898"
},
ticks: {
fontColor: "#989898",
fontSize: 16,
beginAtZero: true
}
}]
},
plugins: {
datalabels: {
anchor: 'center',
font: {
size: 16,
weight: 'bold'
},
formatter: function(value, context) {
return '$' + Number(value).toLocaleString();
},
color: 'white'
}
},
onClick: (evt, item) => {
const idx = chart.getElementAtEvent(event)[0]._index;
console.log(data[idx]);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="myChart" height="80"></canvas>