Excellent and free library from chart.js. I'm transferring my charts from Google charts to chart.js, because I can use them offline and it seems more responsive to window's changes of size. Furthermore I realised that my viewers in China could not see my Google charts because Google services are blocked in China.
I've been reading the documentation regarding stacked vertical bar charts, but I can't figure out, how to make a chart like this. In all examples I saw for stacked bar charts, the number of items is the same for each bar.
Can I make only two vertical stacked datasets? It's because the right bar has more items than the left one. Or do I need n datasets, being n the number of items, of the bar which has more items?
Code
I want to group one dataset per (stacked) bar, but I can't.
var ctx = document.getElementById("barChart").getContext('2d');
var labels = ["standing costs", "running costs"];
var dataset = [
{
type: 'bar',
label: ["cost1", "cost2", "cost3", "cost4"],
data: [1, 2, 1, 3],
stack: "standing costs",
backgroundColor: [
'navy',
'blue',
'aqua',
'teal'
]
},
{
type: 'bar',
label: ["cost5", "cost6", "cost7", "cost8"],
data: [5, 1, 3, 0],
stack: "running costs",
backgroundColor: [
'green',
'lime',
'yellow',
'white'
]
}
];
var options = {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
};
var content = {
type: 'bar',
data: {
labels: labels,
datasets: dataset
},
options
};
new Chart(ctx, content);
#import url("https://cdnjs.cloudflare.com/ajax/libs/colors/1.0/colors.min.css");
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js"></script>
<canvas id="barChart"></canvas>
Quick Solution :
Vertical Stacked Bar Chart
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Standing costs', 'Running costs'], // responsible for how many bars are gonna show on the chart
// create 12 datasets, since we have 12 items
// data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')
// put 0, if there is no data for the particular bar
datasets: [{
label: 'Washing and cleaning',
data: [0, 8],
backgroundColor: '#22aa99'
}, {
label: 'Traffic tickets',
data: [0, 2],
backgroundColor: '#994499'
}, {
label: 'Tolls',
data: [0, 1],
backgroundColor: '#316395'
}, {
label: 'Parking',
data: [5, 2],
backgroundColor: '#b82e2e'
}, {
label: 'Car tax',
data: [0, 1],
backgroundColor: '#66aa00'
}, {
label: 'Repairs and improvements',
data: [0, 2],
backgroundColor: '#dd4477'
}, {
label: 'Maintenance',
data: [6, 1],
backgroundColor: '#0099c6'
}, {
label: 'Inspection',
data: [0, 2],
backgroundColor: '#990099'
}, {
label: 'Loan interest',
data: [0, 3],
backgroundColor: '#109618'
}, {
label: 'Depreciation of the vehicle',
data: [0, 2],
backgroundColor: '#109618'
}, {
label: 'Fuel',
data: [0, 1],
backgroundColor: '#dc3912'
}, {
label: 'Insurance and Breakdown cover',
data: [4, 0],
backgroundColor: '#3366cc'
}]
},
options: {
responsive: false,
legend: {
position: 'right' // place legend on the right side of chart
},
scales: {
xAxes: [{
stacked: true // this should be set to make the bars stacked
}],
yAxes: [{
stacked: true // this also..
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx" width="700"></canvas>
apology for not giving explanation.
updated for v3
<div style="height: 500px">
<canvas id="chart_1" ></canvas>
</div>
<script>
chart = new Chart(document.getElementById('chart_1').getContext('2d'), {
type: 'bar',
data: {
labels: ["One", "Two", "Three"],
datasets: [{
label: 'Blue',
data: [100, 110, 120],
backgroundColor: 'blue',
},
{
label: 'Red',
data: [30, 20, 10],
backgroundColor: 'red',
},
]
},
options: {
plugins: {
title: {
display: true,
text: 'Example',
font: {
size: 14
}
},
},
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
});
</script>
Related
I need the Holiday tooltip to be grouped, that is to say, pressing a tooltip stops seeing all the Holidays. In this way, not having the "Holiday" tooltip repeated twice and showing / hiding with a single tooltip
Is it possible with chart js?
Actual:
Expected:
a single tooltip handling the "Holiday" datasets
Actual code:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple"],
datasets: [
{
label: 'HOLIDAY',
data: [10, 10,10,10,10],
borderWidth: 1,
backgroundColor: "red",
stack: 1
},
{
label: 'HOLIDAY',
data: [10, 10,10,10,10],
borderWidth: 1,
backgroundColor: "red",
stack: 2
},
{
label: 'IN OFFICE',
data: [7, 11, 5, 8, 3],
borderWidth: 1,
backgroundColor: "blue",
stack:1
},
{
label: 'HOME OFFICE',
data: [7, 11, 5, 8, 3],
borderWidth: 1,
backgroundColor: "yellow",
stack:2
}
]
},
options: {
indexAxis: 'y',
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each horizontal bar to be 2px wide
elements: {
bar: {
borderWidth: 2,
}
},
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="400" height="100"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</body>
Am trying to create bar graph with multiple plots using chartjs and the graph is generated successfully but one of the legend is not showing correctly.
Am using Chartjs 2.9.3 version.
One of the bar legendary is showing as circle instead of rectangle box. Kindly let me know if any workaround to get the correct legendary.
Bar graph show circle in the legendary
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [
{
label: 'Label1',
data: [3,4],
type: 'scatter',
backgroundColor: 'red',
pointStyle:'circle',
pointRadius:5
},
{
label: 'Label2',
data: [1,2],
type: 'scatter',
backgroundColor: 'blue',
pointStyle:'triangle',
pointRadius:5
},
{
backgroundColor: 'grey',
label: 'Label3',
data: [1,2],
borderWidth: 1,
type: 'bar'
}
]
},
options: {
responsive:false,
legend: {
labels : {
usePointStyle: true
}
},
title: {
display: true
},
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: '$/MWh'
}
}]
}
}
});
If the usePointstyle flag is set in the legend it defaults to the circle. In V2 this is not configurable for bar charts so you have 2 options
You can switch to a html legend and style that. Or you can update to chart.js version 3 where you can configure it for bar charts:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'yellow'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'pink',
pointStyle: 'rect'
}
]
},
options: {
plugins: {
legend: {
labels: {
usePointStyle: true
}
}
}
}
}
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.5.0/chart.js"></script>
</body>
echarts: bar chart bars are located left and right of the value on the category axis:
How to tell echarts to start the bar with the value on the category axis? Like this:
To clarify the problem, here ist another example. This is a chart of the hourly sum of precipitation. Every bar should show the sum from the bottom to the top of the hour, the data values are conencted to every bottom of the hour.
as you can see, the bars are not starting at 8:00, they are starting at 7:30.
Data: (timestamps are shown in CET)
series: [
{
name: "Niederschlag",
type: "bar",
data: [[1608534000000, 3], [1608537600000, 5], [1608541200000, 2], [1608544800000, 0], [1608548400000, 1] ],
barWidth: '100%'
}
]
It should look like this:
Start point of bar here doesn't matter, you need align labels to left: https://echarts.apache.org/en/option.html#series-bar.label.align
you need a hidden xAxis like below:
option = {
xAxis: [{
type: 'category',
data: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
show: false
}, {
type: 'category',
data: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
boundaryGap: false,
axisTick: { alignWithLabel: true },
position: 'bottom'
}],
yAxis: {
type: 'value'
},
series: [{
data: [120, 200, 150, 80, 70, 110, 130,120,210,110,210],
type: 'bar',
barCategoryGap:'20%',
itemStyle: {
},
xAxisIndex: 0,
backgroundStyle: {
color: 'rgba(220, 220, 220, 0.8)'
}
}]
};
You have not provided the complete chart config, so I recommend using this one. Also pay attention on method useUTC and you need to know that "By default, echarts uses local timezone to formate time labels"
So I see this state of Chart by you data with offset -180:
var myChart = echarts.init(document.getElementById('chart'));
var chartData = [
[1608534000000, 3],
[1608537600000, 5],
[1608541200000, 2],
[1608544800000, 0],
[1608548400000, 1],
];
var option = {
tooltip: {},
xAxis: {
type: 'time',
data: ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
splitNumber: 24,
},
yAxis: {
type: 'value'
},
series: [{
name: "Niederschlag",
type: "bar",
data: chartData,
barWidth: '100%',
}],
useUTC: false,
};
myChart.setOption(option);
<script src="https://cdn.jsdelivr.net/npm/echarts#4.9.0/dist/echarts.min.js"></script>
<div id="chart" style="width: 1024px;height:400px;"></div>
In the example below the y-axis crosses at 1, rather than 0. Is there a way to achieve this in echarts?
It seems to me, literally, you can't do this with basic bar chart because it will break the coordinate system and result will be anything but not a bar chart.
If you need only visual like on attached picture then you can hide xAxis and draw its surrogate with markLine but you will have the troubles with bar positioning (that will fix with stack and transparent bars, see below).
If you need real chart with responsive, zoomable and other opts then in the Echarts you can use custom series for build own chart type (see example).
Example how to make picture like attached:
var myChart = echarts.init(document.getElementById('main'));
var option = {
tooltip: {},
xAxis: {
data: ['Category-1', 'Category-2', 'Category-3', 'Category-4'],
show: true,
axisLine: {
show: true,
lineStyle: {
opacity: 0
}
},
axisTick: {
show: false,
}
},
yAxis: {
max: 4,
min: -1
},
series: [{
name: 'Series-1',
type: 'bar',
stack: 'group',
data: [1, 1, -3],
color: 'rgba(0,0,0, 0)',
}, {
name: 'Series-2',
type: 'bar',
stack: 'group',
data: [{
value: 1,
itemStyle: {
color: 'red'
}
}, {
value: 2,
itemStyle: {
color: 'green'
}
}, {
value: 1,
itemStyle: {
color: 'orange'
}
}],
markLine: {
symbol: "none",
data: [{
silent: false,
yAxis: 1,
lineStyle: {
color: "#000",
width: 1,
type: "solid"
}
}, ],
label: {
show: false,
}
},
}]
};
myChart.setOption(option);
<script src="https://cdn.jsdelivr.net/npm/echarts#4.8.0/dist/echarts.min.js"></script>
<div id="main" style="width: 600px;height:400px;"></div>
P.S. If this not a secret, why you need it?
I want to create a chart.js plugin to create waterfall charts.
I am new to working with chart.js. I was thinking to extend the bar-chart to create a waterfall chart.
The draw function in the bar chart controller is as follows:
draw: function(ease) {
var me = this;
var easingDecimal = ease || 1;
helpers.each(me.getMeta().data, function(rectangle, index) {
var d = me.getDataset().data[index];
if (d !== null && d !== undefined && !isNaN(d)) {
rectangle.transition(easingDecimal).draw();
}
}, me);
},
THe full bar chart controller js file can be found here:
https://github.com/chartjs/Chart.js/tree/master/src/controllers
Since Chart.js v2.9.0., we can use floating bars to easily create waterfall charts. Individual bars may since be specified with the syntax [min, max].
Given an array of values [3, 5, 4, 2, 6], we need to produce the following data (last entry being the computed value for the 'Total' bar):
[[0, 3], [3, 8], [8, 12], [12, 14], [14, 20], 20]
The only additional thing left to do is defining a tooltips.callback function that computes the correct value to be shown in the tooltips.
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
const v = data.datasets[0].data[tooltipItem.index];
return Array.isArray(v) ? v[1] - v[0] : v;
}
}
},
Please have a look at the following code sample that produces a waterfall chart out of the baseData array.
let baseData = [
{ label: 'A', value: 3 },
{ label: 'B', value: 5 },
{ label: 'C', value: 4 },
{ label: 'D', value: 2 },
{ label: 'E', value: 6 }
];
const labels = baseData.map(o => o.label).concat('Total');
const data = [];
let total = 0;
for (let i = 0; i < baseData.length; i++) {
const vStart = total;
total += baseData[i].value;
data.push([vStart, total]);
}
data.push(total);
const backgroundColors = data.map((o, i) => 'rgba(255, 99, 132, ' + (i + (11 - data.length)) * 0.1 + ')');
new Chart('waterfall', {
type: 'bar',
data: {
labels: labels,
datasets: [{
data: data,
backgroundColor: backgroundColors,
barPercentage: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
const v = data.datasets[0].data[tooltipItem.index];
return Array.isArray(v) ? v[1] - v[0] : v;
}
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="waterfall" height="200"></canvas>
If the chart should start with the 'Total' bar, simply reverse labels, data and backgroundColors arrays as follows.
data: {
labels: labels.reverse(),
datasets: [{
data: data.reverse(),
backgroundColor: backgroundColors.reverse(),
...
I created a chartjs plugin for waterfall charts.
See https://github.com/MartinDawson/chartjs-plugin-waterfall
This plugin works by checking if any of your datasets contain a property called dummyStack that is set to true. The stack property must be used in conjunction with dummyStack for this plugin to work properly. If dummyStack is true then it hides the label, tooltip and sets the color invisible. When you use stacking with this it creates the affect of a floating bar as shown in the image above that we can use for waterfall charts as chartjs-2 doesn't support waterfall charts by default.
import waterFallPlugin from 'chartjs-plugin-waterfall';
var chart = new Chart(ctx, {
plugins: [waterFallPlugin]
});
const data = {
datasets: [
{
label: 'Closing Costs',
data: [50],
backgroundColor: '#e8cdd7',
stack: 'stack 1',
},
{
label: 'Purchase Price',
data: [700],
backgroundColor: '#d29baf',
stack: 'stack 1',
},
{
data: [200],
dummyStack: true,
stack: 'stack 2',
},
{
label: 'Opening Loan Balance',
data: [550],
backgroundColor: '#bb6987',
stack: 'stack 2',
},
{
label: 'Initial Cash Investment',
data: [200],
backgroundColor: '#a53860',
stack: 'stack 3',
},
],
};
It also has line steps from bar to bar.
You can use the plugin recommented by Chart.JS https://github.com/everestate/chartjs-plugin-waterfall (Ref: https://www.chartjs.org/docs/2.7.2/notes/extensions.html)
Installation
npm install --save chartjs-plugin-waterfall
Usage
import waterFallPlugin from 'chartjs-plugin-waterfall';
var chart = new Chart(ctx, {
plugins: [waterFallPlugin]
});