ECharts - Getting a single splitLine to render in a stacked bar chart - echarts

Trying to get a single split line to render on a stacked bar graph.
Here's the code:
options = {
tooltip: {
trigger: 'item',
axisPointer: {
type: 'shadow'
}
},
legend: {
data: ['Graph 1', 'Graph 2']
},
grid: {
left: '7%',
right: '5%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: [40, 41, 42, 43, 44],
axisLabel: {
interval: 1
},
splitLine: {
show: true,
interval: function (param) {
//return param === 1; //what I'm trying to get it to do
return param > 0 && param < 2; //this doesn't work
//return param > 0; //this works, but adds a split line to everything above 1 as well, not what I want. vice versa (param < 2) also works, but again not what I want
},
lineStyle: {
type: 'dashed',
width: 2,
color: '#767676'
}
}
}
],
yAxis: [
{
type: 'value',
name: 'Y',
nameLocation: 'middle',
nameTextStyle: {
padding: [0, 0, 8, 0],
color: '#767676',
fontSize: 14
},
axisTick: {
show: false
},
axisLabel: {
show: false
},
splitLine: {
show: false
}
}
],
series: [
{
name: 'Graph 1',
type: 'bar',
barWidth: 20,
stack: 'Graph',
itemStyle: {
color: '#db0011'
},
data: [8000, 10000, 12000, 16000, 20000]
},
{
name: 'Graph 2',
type: 'bar',
barWidth: 20,
barGap: '-100%',
stack: 'Graph',
itemStyle: {
color: '#00a69d'
},
data: [4000, 5000, 6000, 8000, 10000]
}
]
};
As per the above code,
param > 0 works but will add a split line to everything beyond 1 (1 and 2)
likewise, param < 2 will add a split line to everything before 2 (0 and 1)
param > 0 and param < 2 doesn't work (no split line appears)
setting a fixed number causes a split line to appear at the end of the graph as well, despite not being in the right interval (e.g. if my items went from 40 - 80 and I set an interval of 7, then the split line would appear before 47, 54, 61, 68, 75 and on 40 and 80)
How do I get a single split line to appear?
I've also seen Echarts how do you add dashed vertical line in between specific bars on bar chart?, however I don't have enough knowledge on how to modify this to work with a stacked bar chart.
How I want it to look like:

The way I ended up resolving this is:
var option = {
tooltip: {
trigger: 'item',
axisPointer: {
type: 'shadow'
}
},
legend: {
data: ['Graph 1', 'Graph 2']
},
grid: {
left: '7%',
right: '5%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: [40, '', 41, '', 42, '', 43, '', 44],
axisLabel: {
interval: 1
},
splitLine: {
show: false
}
}
],
yAxis: [
{
type: 'value',
name: 'Y',
nameLocation: 'middle',
nameTextStyle: {
padding: [0, 0, 8, 0],
color: '#767676',
fontSize: 14
},
axisTick: {
show: false
},
axisLabel: {
show: false
},
splitLine: {
show: false
}
}
],
series: [
{
name: 'Graph 1',
type: 'bar',
barWidth: 20,
stack: 'Graph',
data: [8000, 0, 10000, 0, 12000, 0, 16000, 0, 20000],
markLine: {
silent: true,
symbol: 'none',
label: {
show: false
},
data: [
{
name: "Test",
xAxis: 2.5,
lineStyle: {
color: '#767676',
width: 2,
type: 'dashed'
}
},
]
}
},
{
name: 'Graph 2',
type: 'bar',
barWidth: 20,
barGap: '-100%',
stack: 'Graph',
data: [4000, 0, 5000, 0, 6000, 0, 8000, 0, 10000]
}
]
};
A few things to note:
Add a bunch of empty string entries for your labels (x-axis). As can be seen above, data is [40, '', 41, '', 42, '', 43, '', 44] instead of [40, 41, 42, 43, 44].
Add zeroes in your graph series relative to where you inserted empty string labels in your x-axis data above (e.g. 4000, 0, 5000, 0, 6000, 0, 8000, 0, 10000). Do this for each graph you have.
In any of the graphs, insert the above markLine syntax I added to Graph 1. You will need to adjust the value of xAxis until you get the middle point.
Demo: https://jsfiddle.net/k9hgj5zb/1/
Credits to this link: Draw horizontal target line using EChart.JS

Related

Apache echarts scatter: assign label to each point

I am building an echarts scatter graph that contains 6 points. I would like to manually assign a label to each point, like I did with the label of X and Y axis.
Is there a way to achieve this? I searched in Apache Echarts docs but I did not find any useful setting for assigning a label to "data" values.
Here is the source code of my graph:
option = {
xAxis: {
data: ['Low', 'Med', 'High'],
name: "Value",
},
yAxis: {
min: '5',
name: "Score",
},
series: [
{
type: 'scatter',
symbolSize: 20,
data: [
[2,9.8],
[1,8.8],
[2,5.9],
[1,9.8],
[1,10.0],
[3,9.8],
[2,10.0],
[1,9.8],
[2,5.9],
[1,9.8]
],
label: {
show: true,
position: 'right',
color: "black",
fontSize: 16,
},
}
],
grid:{
show: true,
backgroundColor: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: 'rgb(255, 102, 102)'
},
{
offset: 1,
color: 'rgb(153, 255, 153)'
}])
},
};
You could specify the labels as an additional value in the data array:
data: [
[ 2, 9.8, "label1" ],
[ 1, 8.8, "label2" ],
...
Then use a formatter function in your label definition, to select the third element of the data array as the label:
label: {
...
formatter: function(d) {
return d.data[2];
}
I also found this solution, working as well as Chris one:
series: [
{
type: 'scatter',
symbolSize: 15,
data: [
{value: [2,9.8] , name: 'value1'},
{value: [1,8.8] , name: 'value2'},
{value: [2,5.9] , name: 'value3'},
],
label: {
show: true,
position: 'right',
formatter: params => params.name,
color: "black",
fontSize: 16,
},

ECharts bar chart backed by dataset; tooltip with several values

I'd like to show bar chart with categories on x-axis (say months), multiple series and each bar element containing multiple data points (value shown on y-axis, the rest in tooltip).
It's relatively easy to do it using series.data:
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
// Use axis to trigger tooltip
type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
}
},
xAxis: {
type: 'category'
},
yAxis: {
type: 'value'
},
series: [
{
name: 'Series A',
type: 'bar',
label: {
show: true
},
data: [
['Jul', 320, 2],
['June', 119, 4]],
encode: {
tooltip: [0,1,2]
}
}
,
{
name: 'Series B',
type: 'bar',
label: {
show: true
},
data: [
['Jul', 420, 3],
['June', 123, 5]],
encode: {
tooltip: [0,1,2]
}
}
]
};
I'm wondering how it can be refactored best to use dataset? I have two ideas, I wonder what are pros & cons.. Maybe there is other, cleaner way to express it.
Ideally instead of one big array I'd prefer to have array of objects so dimensions are named.
Solution: One dataset, shifting indices
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
// Use axis to trigger tooltip
type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
}
},
legend: {},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category'
//, data: ['Jul', 'June']
},
yAxis: {
type: 'value'
},
dataset: {
source: [
['Jul', 320, 2, 420, 3],
['June', 119, 4, 123, 5]]
},
series: [
{
name: 'Series A',
type: 'bar',
label: {
show: true
},
encode: {
y: 1,
tooltip: [0,1,2]
}
}
,
{
name: 'Series B',
type: 'bar',
label: {
show: true
},
encode: {
y: 3,
tooltip: [0,3,4]
}
}
]
};
With named dimensions it would look like:
dataset: {
source: [
[month:'Jul', SeriesA_dim1: 320, SeriesA_dim2: 2, SeriesB_dim1: 420, SeriesB_dim2: 3],
[month:'Jun', SeriesA_dim1: 119, SeriesA_dim2: 4, SeriesB_dim1: 123 SeriesB_dim2: 5],
},
....
encode: {
y: 'SeriesB_dim1',
tooltip: ['month','SeriesB_dim1','SeriesB_dim2']
}
Solution 2: Multiple datasets
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
// Use axis to trigger tooltip
type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
}
},
legend: {},
xAxis: {
type: 'category'
},
yAxis: {
type: 'value'
},
dataset: [{
source: [
['Jul', 320, 2],
['June', 119, 4]]
},
{
source: [
['Jul', 420, 3],
['June', 123, 5]]
}],
series: [
{
name: 'Series A',
type: 'bar',
label: {
show: true
},
// data: [
// ['Jul', 320, 2],
// ['June', 119, 4]],
encode: {
tooltip: [0,1,2]
}
}
,
{
name: 'Series B',
type: 'bar',
label: {
show: true
},
// data: [
// ['Jul', 420, 3],
// ['June', 123, 5]],
datasetIndex: 1,
encode: {
tooltip: [0,1,2]
}
}
]
};
With named dimensions it would look like:
dataset: [{
source: [
[month:'Jul', dim1: 320, dim2: 2],
[month:'June', dim1: 119, dim2: 4]]
},
{
source: [
[month:'Jul', dim1: 420, dim2: 3],
[month:'June', dim1: 123, dim2: 5]]
}],
....
encode: {
y: 'dim1', // the default would be likely working as well
tooltip: ['month','dim1','dim2']
}

Using ChartJS to create a multiple grouped bar chart - see picture below

I am testing out HighCharts and ChartJS to see which to use. For Highcharts, I was able to find a hack to create a bar chart that had double grouping on the x-axis.
This is what I want to look like:
I am new to both charting JS options and wonder if there is a way to do this in ChartJS.
I have the datasets something like this:
xAxis: {
categories: [{
name: "Total",
categories: ["2004", "2008", "2012"]
}, {
name: "Lower than 2.50",
categories: ["2004", "2008", "2012"]
}]
},
yAxis: {
min: 0,
title: {
text: 'Percent (%)'
}
},
series: [{
name: 'Male',
data: [42.4, 43.0, 43.0, 50.3, 49.4, 48.4]
}, {
name: 'Female',
data: [57.6, 57.0, 57.0, 49.7, 50.6, 51.6]
}]
Essentially I need a nest series on the x-axis and I am open to plugins or code from Github to do this.
You can make use of the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code, I use the afterDraw hook to draw the category labels and the delimiter lines.
new Chart('myChart', {
type: 'bar',
plugins: [{
afterDraw: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let xCenter = (xAxis.left + xAxis.right) / 2;
let yBottom = chart.scales['y-axis-0'].bottom;
ctx.textAlign = 'center';
ctx.font = '12px Arial';
ctx.fillText(chart.data.categories[0], (xAxis.left + xCenter) / 2, yBottom + 40);
ctx.fillText(chart.data.categories[1], (xCenter + xAxis.right) / 2, yBottom + 40);
ctx.strokeStyle = 'lightgray';
[xAxis.left, xCenter, xAxis.right].forEach(x => {
ctx.beginPath();
ctx.moveTo(x, yBottom);
ctx.lineTo(x, yBottom + 40);
ctx.stroke();
});
ctx.restore();
}
}],
data: {
labels: ['2004', '2008', '2012', '2016', '2004', '2008', '2012', '2016'],
categories: ['Total', 'Lower than 2.50'],
datasets: [{
label: 'Male',
data: [42.4, 43.0, 43.0, 50.3, 49.4, 48.4, 51.2, 51.8],
backgroundColor: 'rgba(124, 181, 236, 0.9)',
borderColor: 'rgb(124, 181, 236)',
borderWidth: 1
},
{
label: 'Female',
data: [57.6, 57.0, 57.0, 49.7, 50.6, 51.6, 53.7, 54.6],
backgroundColor: 'rgba(67, 67, 72, 0.9)',
borderColor: 'rgb(67, 67, 72)',
borderWidth: 1
}
]
},
options: {
legend: {
position: 'bottom',
labels: {
padding: 30,
usePointStyle: true
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 80,
stepSize: 20
},
scaleLabel: {
display: true,
labelString: 'Percent (%)'
}
}],
xAxes: [{
gridLines: {
drawOnChartArea: false
}
}]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>
You have to define a second x-axis and play around with the many ticks and gridLines options.
Please take a look at below runnable code and see how it could be done. This is obviously only a draft and needs to optimized and made more generic.
new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: ['2004', '2008', '2012', '2004', '2008', '2012'],
datasets: [{
label: 'Male',
data: [42.4, 43.0, 43.0, 50.3, 49.4, 48.4],
backgroundColor: 'rgba(124, 181, 236, 0.9)',
borderColor: 'rgb(124, 181, 236)',
borderWidth: 1
},
{
label: 'Female',
data: [57.6, 57.0, 57.0, 49.7, 50.6, 51.6],
backgroundColor: 'rgba(67, 67, 72, 0.9)',
borderColor: 'rgb(67, 67, 72)',
borderWidth: 1
}
]
},
options: {
legend: {
position: 'bottom',
labels: {
usePointStyle: true
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 80,
stepSize: 20
},
scaleLabel: {
display: true,
labelString: 'Percent (%)'
}
}],
xAxes: [{
gridLines: {
drawOnChartArea: false
}
},
{
offset: true,
ticks: {
autoSkip: false,
maxRotation: 0,
padding: -15,
callback: (v, i) => {
if (i == 1) {
return 'Total';
} else if (i == 4) {
return 'Lower than 2.50';
} else {
return '';
}
}
},
gridLines: {
drawOnChartArea: false,
offsetGridLines: true,
tickMarkLength: 20,
color: ['white', 'white', 'white', 'lightgray', 'white', 'white', 'lightgray']
}
}
]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>

Draw points and lines inside a bar in bar chart

Who know how to draw lines and points inside a bar something like this:
You can draw the lines as floating bars where individual bars are specified with the syntax [min, max], same as you already do for your your other bars. Given an array of number values, the "line" data can be produced with Array.map() as follows.
data: [110, 150, 140, 100, 120].map(v => [v - 1, v + 1])
Then you need to define individual stacked xAxes for the "bar" and the "line" datasets. In order to have the original "line" values displayed in the tooltips, a toolips.callback.label function is also needed.
The points can be defined in an additional dataset of type 'scatter'.
Please have a look at below runnable code snippet.
new Chart("chart", {
type: "bar",
data: {
labels: ["4", "3", "2", "1", "0"],
datasets: [{
label: "Bars",
backgroundColor: "rgba(0, 255, 0, 0.2)",
data: [[20, 100], [50, 180], [60, 120], [10, 130], [70, 140]],
xAxisID: "x-axis-actual",
order: 1
},
{
label: "Lines",
backgroundColor: "rgb(0, 0, 0)",
data: [90, 150, 110, 90, 120].map(v => [v - 1, v + 1]),
xAxisID: "x-axis-target",
order: 2
},
{
label: "Points",
backgroundColor: "rgb(255, 255, 255)",
borderColor: "rgb(0, 0, 0)",
data: [80, 110, 90, 100, 120],
type: "scatter"
}
]
},
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
const dataset = data.datasets[tooltipItem.datasetIndex];
const v = dataset.data[tooltipItem.index];
return dataset.label + ': ' + (tooltipItem.datasetIndex == 1 ? (v[1] + v[0]) / 2 : tooltipItem.value);
}
}
},
scales: {
xAxes: [{
id: "x-axis-target",
stacked: true
},
{
display: false,
offset: true,
stacked: true,
id: "x-axis-actual",
gridLines: {
offsetGridLines: true
}
}
],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="120"></canvas>

Apache ECharts: Rotated labels get cropped

I'm trying to use rotated labels in my graph. However, the labels are getting cropped. How can I make more space in the bottom so that the labels can fit?
options = {
xAxis: {
type: "category",
data: axis,
axisLabel: {
show: true,
interval: 0,
rotate: 45,
},
axisTick: {
show: true,
interval: 0
}
},
yAxis: {
type: "value",
data: axis,
min: 1,
minInterval: 1,
maxInterval: 1,
max: 15,
axisTick: {
interval: 1
}
},
series: [
{
type: "bar",
stack: "minmax",
itemStyle: {
normal: {
color: "rgba(0,0,0,0)"
}
},
data: maxs
},
{
type: "bar",
stack: "minmax",
data: mins,
itemStyle: { color: "#63869e" }
},
{
symbolSize: 20,
data: scatter,
type: "scatter",
itemStyle: { color: "black" },
},
]
};
To contain the label you can use:
options = {
grid: {
containLabel: true,
}
}
Space can be added with grid option bottom:
options = {
grid: {
bottom: 100,
}
}