As you can see my bars are not covering the entire width of the label 'column'.
My tooltip only shows if I am exactly hovering the bar, or, if I remove the bars, exactly on the line point.
options: {
plugins: {
legend: { display: false },
title: { display: false },
tooltip: {
displayColors: false, backgroundColor: '#ffffff',
bodyColor: '#595f69', bodyFont: {size: 14},
borderColor: '#595f69', borderWidth: 1,
titleFont: {size: 0}
}
},
responsive: true, aspectRatio: 4,
scales: {
y: { display: true, suggestedMin: 0, suggestedMax: 80, ticks: { stepSize: 20 } },
y1: {display: false, suggestedMin: 0, suggestedMax: 80, ticks: { stepSize: 2 }},
x: { grid: { drawBorder: false, display: false } }
I tried plugins like chartjs crosshair, but don't manage to make it work with typescript.
How can I make it so that anywhere my mouse hover in the label 'column' area, the tooltip displays?
You can set the intersect property to false to always get the tooltip without needing to intersect the bar exactly:
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
}]
},
options: {
plugins: {
tooltip: {
intersect: 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.5.0/chart.js"></script>
</body>
You can make your own tooltip by editing the callbacks, i had to get the nearest values around my cursor, from all datasets, on my line chart. this works for me on Chartjs 2.9.3:
tooltips: {
mode: "x",
position: "nearest",
intersect: false,
callbacks: {
beforeBody: function(tooltipItems, allData) {
let x = tooltipItems[0].x; // get x coordinate
let datasets = allData.datasets; // datasets
let values = [];
for (i in datasets) {
let dataset = datasets[i];
let meta = this._chart.getDatasetMeta(i); // dataset metadata
let xScale = this._chart.scales[meta.xAxisID]; // dataset's x axis
let xValue = xScale.getValueForPixel(x); // we get the x value on the x axis with x coordinate
let data = dataset.data // data
// search data for the first value with a bigger x value
let index = data.findIndex(function(o) {
return o.x >= xValue;
});
let value = data[index]; // this is our nearest value
// format label
if (isNaN(value.ymax)) {
values.push(`${dataset.label}: ${value.y}\n`);
} else {
values.push(`${dataset.label}: ${value.y}, min: ${value.ymin}, max: ${value.ymax}\n`)
}
}
return values.join(""); // return label
},
label: function() { // this needs to be empty
},
}
},
Related
I have a bar chart that always shows 4 bars. The bars are coloured dynamically. It looks like the coloured box takes its colour from the first data. I would like to use the colour from the 4th (last) data value. Maybe the options:plugins:legend:label:sort function helps but I don't understand what it does.
options
const options = {
scales: {
x: {
grid: {
display: false,
color: 'rgba(0,0,0)'
}
},
y: {
display: false,
min: 0,
max: 4
},
},
plugins: {
legend: {
position: 'bottom'
}
}
}
So I don't know if I can change the data that the box color comes from, or if there is a config option somewhere where I can change it manually.
You can use the generateLabels function as described here.
Please take a look at below runnable sample code and see how it works.
new Chart('myChart', {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'My Dataset',
data: [300, 50, 100],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
}]
},
options: {
responsive: false,
plugins: {
legend: {
labels: {
generateLabels: chart => {
let ds = chart.data.datasets[0];
let color = ds.backgroundColor[ds.backgroundColor.length - 1];
return [{
datasetIndex: 0,
text: ds.label,
fillStyle: color,
strokeStyle: color
}];
}
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart" height="180"></canvas>
Following up with #uminder's answer, if you want to keep the hide/show chart and the line-through style after clicking on the legend, you can add the following line:
options: {
responsive: false,
plugins: {
legend: {
labels: {
generateLabels: chart => {
let ds = chart.data.datasets[0];
let color = ds.backgroundColor[ds.backgroundColor.length - 1];
return [{
datasetIndex: 0,
text: ds.label,
fillStyle: color,
strokeStyle: color,
+ hidden: !chart.isDatasetVisible(0)
}];
}
}
}
}
}
Im using the e-charts libary for creating a bar chart for my data .
like so :
option.series = [
{
name: 'buy',
type: 'bar',
stack: 'one',
data: Object.values(chartData?.data || {}).map(elem => -elem.buy?.total),
color: colors.bought,
label: {
show: true,
position: "bottom",
formatter: (value) => Math.round(Math.abs(value.data))
},
tooltip: {
formatter: (data) => Math.abs(data.value).toString()
},
// barWidth:this.data
},
{
name: 'sell',
type: 'bar',
stack: 'one',
data: Object.values(chartData?.data || {}).map(elem =>elem.sell?.total),
color: colors.sold,
label: {
show: true,
position: "top",
formatter: (value) => Math.round(Math.abs(value.data))
},
tooltip: {
formatter: (data) => Math.abs(data.value).toString()
},
},
{
name: 'profite',
type: 'bar',
stack: 'two',
barGap: '-100%',
z: 100,
data: Object.values(chartData?.data || {}).map(elem => elem.sell?.profit),
color: colors.profit,
label: {
show: true,
position: "insideTop",
textBorderWidth: -1,
offset: [0, -20],
formatter: (value) => Math.round(Math.abs(value.data))
},
tooltip: {
formatter: (data) => Math.abs(data.value).toString()
},
},
]
im trying to set a different width for each bar depending on the value of each bar .
on data property i get a list of numbers rendering .
When i try to add a barWidth property all i can do is change all of the bars in the same chrts like so for example:
barWidth: ${getBarWidth((Object.values(chartData?.data || {}).map((elem) => elem.sell?.amount)))}%
so i returne a different value of my data each time but it didnt changed each bar according to its value (either buy, sell and so on).
Thanks in adavance.
As you pointed out, barWidth sets the width of all the bars of a bar series. And I don't think there is a way to set the width of each bar in the same bar series.
What you should use instead is a custom series.
Custom series have a parameter called renderItem, where you write the render logic of the chart. It's where you'll be able to display custom shapes (custom sized bar in your case), using graphics.
Here is an example I found on their website, doing pretty much what you're looking for.
var container = document.getElementById('main');
var chart = echarts.init(container);
const colorList = [
'#4f81bd',
'#c0504d',
'#9bbb59',
'#604a7b',
'#948a54',
'#e46c0b'
];
const data = [
[10, 16, 3, 'A'],
[16, 18, 15, 'B'],
[18, 26, 12, 'C'],
[26, 32, 22, 'D'],
[32, 56, 7, 'E'],
[56, 62, 17, 'F']
].map(function (item, index) {
return {
value: item,
itemStyle: {
color: colorList[index]
}
};
});
chart.setOption({
title: {
text: 'Profit',
left: 'center'
},
tooltip: {},
xAxis: {
scale: true
},
yAxis: {},
series: [
{
type: 'custom',
renderItem: function (params, api) {
var yValue = api.value(2);
var start = api.coord([api.value(0), yValue]);
var size = api.size([api.value(1) - api.value(0), yValue]);
var style = api.style();
return {
type: 'rect',
shape: {
x: start[0],
y: start[1],
width: size[0],
height: size[1]
},
style: style
};
},
label: {
show: true,
position: 'top'
},
dimensions: ['from', 'to', 'profit'],
encode: {
x: [0, 1],
y: 2,
tooltip: [0, 1, 2],
itemName: 3
},
data: data
}
]
});
#main {
width: 600px;
height: 400px;
}
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.3.2/echarts.min.js"></script>
<div id="main"></div>
</body>
</html>
chart
const data = {
labels: Array(coordinates.length).fill("l"),
datasets: buildDataset(),
options: {
animation: false,
scales: {
// ???????
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
},
maintainAspectRatio: false,
scales: {
myScale: {
position: 'left',
}
},
elements: {
point:{
radius: 0
}
}
}
}
return (
<Chart>
<Line
data={data}
width={50}
height={20}
options={data.options}>
</Line>
</Chart>
)
// ~~~~~
let obj = {
label: stops[0].miles == 0 ? index : index + 1,
data: points,
backgroundColor: colors[index],
tension: 0.4,
fill: true
}
These charts are built from an array of obj objects. The points variable that data refers is an array of object like: [{x: 0, y: 10257}, {x: 1, y: 10245}]
How do I get my line chart to display these different datasets side by side? I assume it has something to do with the scales parameter but wasn't able to find anything that worked in the docs.
Thanks!
For the object notation to work chart.js needs values to plot them against (not the index in the array) so you cant just provide an array containing only the value l.
You can either provide a labels array containing increasing numbers to which you match it or remove it and set your x scale to linear.
Labels example:
var options = {
type: 'line',
data: {
labels: [0, 1, 2, 3],
datasets: [{
label: '# of Votes',
data: [{
x: 0,
y: 4
}, {
x: 1,
y: 6
}, {
x: 2,
y: 2
}],
borderColor: 'pink'
},
{
label: '# of Points',
data: [{
x: 2,
y: 2
}, {
x: 3,
y: 3
}],
borderColor: 'blue'
}
]
},
options: {
scales: {}
}
}
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>
Linear example:
var options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [{
x: 0,
y: 4
}, {
x: 1,
y: 6
}, {
x: 2,
y: 2
}],
borderColor: 'pink'
},
{
label: '# of Points',
data: [{
x: 2,
y: 2
}, {
x: 3,
y: 3
}],
borderColor: 'blue'
}
]
},
options: {
scales: {
x: {
type: 'linear'
}
}
}
}
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>
i am trying to highlight part of a label from the axis labels based on what the user has searched for.
However the label is being rendered as text so the html tags are shown like plain text. any ideas on how to achieve this?
You can use the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw text of different styles underneath each bar.
When drawing your own tick labels, probably want to define the text rotation. Further you need to instruct Chart.js not to display the default labels. This can be done through the following definition inside the chart options.
scales: {
xAxes: [{
ticks: {
display: false,
rotation: 40
}
}],
You also need to define some padding for the bottom of the chart, otherwise you won't see your custom tick labels.
layout: {
padding: {
bottom: 60
}
},
Please take a look at below code sample and see how it works. Tick labels that need to be drawn with two different styles are separated with a semicolon inside data.labels.
new Chart(document.getElementById('myChart'), {
type: 'bar',
plugins: [{
afterDraw: chart => {
let ctx = chart.chart.ctx;
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
chart.data.labels.forEach((l, i) => {
let labelTokens = l.split(';');
let rotation = xAxis.options.ticks.rotation * -Math.PI / 180;
let x = xAxis.getPixelForValue(l);
if (labelTokens.length == 2) {
ctx.save();
let width = ctx.measureText(labelTokens.join(' ')).width;
ctx.translate(x, yAxis.bottom + 10);
ctx.rotate(rotation);
ctx.font = 'italic 12px Arial';
ctx.fillStyle = 'blue';
ctx.fillText(labelTokens[0], -width, 0);
ctx.restore();
}
ctx.save();
let labelEnd = labelTokens[labelTokens.length - 1];
let width = ctx.measureText(labelEnd).width;
ctx.translate(x, yAxis.bottom + 10);
ctx.rotate(rotation);
ctx.font = '12px Arial';
ctx.fillText(labelEnd, -width, 0);
ctx.restore();
});
}
}],
data: {
labels: ['NASTY!!;Errors', 'Warnings'],
datasets: [{
label: 'Result',
data: [30, 59],
fill: false,
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)'],
borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)'],
borderWidth: 1
}]
},
options: {
layout: {
padding: {
bottom: 60
}
},
legend: {
display: false
},
tooltips: {
callbacks: {
title: tooltipItem => tooltipItem[0].xLabel.split(';').join(' ')
}
},
scales: {
xAxes: [{
ticks: {
display: false,
rotation: 40
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
canvas {
max-width: 250px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" width="10" height="8"></canvas>
I am trying to create a chart like this. Below is my chart code. However, I am unable to set a different color in the second bar. The first color in the first bar gets set in the second bar.
self.chart = {
type: 'horizontal-bar',
options: {
responsive: true,
maintainAspectRatio: false,
tooltips: {
enabled: true,
callbacks: {
label: function (tooltipItem, _) {
return $filter('number')(tooltipItem.xLabel);
}
}
},
events: ['click', 'mousemove'],
hover: {
onHover: function(item, chartElement) {
item.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
}
},
scales: {
xAxes: [{
scaleLabel: {
stacked: true,
display: true,
labelString: "Test"
},
ticks: {
stacked: true,
beginAtZero: true,
maxRotation: 0,
minRotation: 0,
callback: function (value) {
return $filter('number')(value);
}
}
}]
}
},
data: [[2,12], [5]],
labels: labels,
colors: [chartBlue, chartGreen],
datasetOverride: [{ stack: 1, fill: false }, { stack: 1, fill: false }]
}
This is the result I am getting.
I need to set a different color (for example yellow) in the second bar.
With colors you define the colors for datasets. With two colors you define two datasets. With your two arrays in data you have two datasets, that's why you can't see an additional color.
You need a third dataset for a third color, with 0 at the labels where you don't want a bar.
Check out the following example (Working example at JSBin):
var config = {
type: 'bar',
data: {
labels: ["January", "February", "March"],
datasets: [{
label: 'Dataset 1',
backgroundColor: 'black',
data: [0, 8, 4]
}, {
label: 'Dataset 2',
backgroundColor: "red",
data: [6, 2, 8],
}, {
label: 'Dataset 3',
backgroundColor: "blue",
data: [3, 0, 0]
}]
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
Have you tried to add more data?
data: [[2,12], [5], [1], [4], [3]],
labels: labels,
colors: [chartBlue, chartGreen],
Try it and see what happens to the chart :)