i'm running through an issue with react-chartjs2. I want somehow to change the z-index of the tooltip. I can't find a property from the documentation so i was wondering if you know a proper solution. Here is a screenshot of my doughnut chart
You can see the issue i mentiom. Half of the tooltip is now shown. I really appreciate your help
Here is my code:
<Doughnut
data={sectorsData}
width={250}
height={250}
redraw
options={{
legend: {
display: false
},
maintainAspectRatio: true,
responsive: true,
cutoutPercentage: 80,
animation: {
animateRotate: false,
animateScale: false
},
elements: {
center: {
textNumber: `${sectorsCounter}`,
text: intl.formatMessage({ id: 'pie.sectors' }),
fontColor: '#656566',
fontFamily: 'EurobankSans',
fontStyle: 'normal',
minFontSize: 25,
maxFontSize: 25,
}
},
/*eslint-disable */
tooltips: {
custom: (tooltip) => {
tooltip.titleFontColor = '#656566';
tooltip.titleFontFamily = 'EurobankSans';
tooltip.bodyFontColor = '#656566';
tooltip.bodyFontFamily = 'EurobankSans';
tooltip.backgroundColor = '#eaeeef';
},
/* eslint-enable */
callbacks: {
title: (tooltipItem, data) => {
const titles = data.datasets[tooltipItem[0]
.datasetIndex].titles[tooltipItem[0].index];
return (
titles
);
},
label: (tooltipItem, data) => {
const labels =
NumberFormatter(data.datasets[tooltipItem.datasetIndex]
.labels[tooltipItem.index],
2,
decimalSep,
thousandSep
);
return (
labels
);
},
afterLabel: (tooltipItem, data) => {
const afterLabels = data.datasets[tooltipItem.datasetIndex]
.afterLabels[tooltipItem.index];
return (
afterLabels
);
},
},
},
}}
/>
If you don't want to make custom Tooltip, then you can try with tooltip settings to make it shorter/smaller:
You can remove extra/unwanted elements from the tooltip. And also can remove extra spacing.
tooltips: {
"enabled": true,
displayColors: false,
caretSize: 0,
titleFontSize: 9,
bodyFontSize: 9,
bodySpacing: 0,
titleSpacing: 0,
xPadding: 2,
yPadding: 2,
cornerRadius: 2,
titleMarginBottom: 2,
callbacks: {
title: function () { }
}
}
Apply a custom className or id for the component and simply set a higher z-index for your chart's canvas element.
Judging from the code, something like this should work:
<div id="my-doughnut-chart-1">
<Doughnut
...props
/>
</div>
CSS:
#my-doughnut-chart-1 canvas {
z-index: 9999 // just an example z-index, change it according to your project
}
Related
I used apexcharts.js for making chartbar on js. So i want to change cursor to pointer. help please! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
my-code!
var options = {
series: [{
name: 'series1',
data: [60, 85, 75, 120, 100, 109, 97]
}],
toolbar: {
show: false,
},
chart: {
height: 350,
type: 'area',
fontFamily: 'Proxima Nova',
toolbar: {
show: false
},
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth'
},
xaxis: {
categories: ["Янв", "Фев", "Март", "Апр", "Май", "Июнь", "Июль", "Авг", "Сен", "Окт", "Ноя", "Дек"]
},
tooltip: {
x: {
format: 'dd/MM/yy HH:mm'
},
},
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
I had encountered the same problem. I will present you two solutions:
1st method : Found on Github
You can set the cursor to point with:
chart: {
...
events: {
dataPointMouseEnter: function(event) {
event.path[0].style.cursor = "pointer";
}
}
}
See more details in this github link : https://github.com/apexcharts/apexcharts.js/issues/1466
2nd method : My own method
You can target the class name of the apexchart component via Inspector, then at the code level add the following property to this class :
cursor: pointer
Example :
// Change cursor on hover
.apexcharts-pie {
cursor: pointer;
}
I had same problem. Here is two solutions:
chart: {
width: 320,
type: ...,
events: {
dataPointMouseEnter: function(event) {
event.target.style.cursor = "pointer";
// or
event.fromElement.style.cursor = "pointer";
}
},
}
I want open a dialog when clicking on chart js label. This is the dataset code:-
const data = {
datasets: [
{
label: 'Reviews',
backgroundColor: theme.palette.primary.main,
data: dataProp.reviews,
barThickness: 12,
maxBarThickness: 10,
barPercentage: 0.5,
categoryPercentage: 0.5
},
{
label: 'Talents',
backgroundColor: theme.palette.secondary.main,
data: dataProp.talents,
barThickness: 12,
maxBarThickness: 10,
barPercentage: 0.5,
categoryPercentage: 0.5
}
],
labels
};
This is the screenshot the chart created.
I know how to set onclick on legend but how can i set an onClick on labels ?
I Tried this in option but it is not working and giving me error
const options = {
responsive: true,
maintainAspectRatio: false,
animation: false,
cornerRadius: 20,
legend: {
display: false
},
layout: {
padding: 0
},
scales: {
xAxes: [
{
}
],
yAxes: [
{
}
]
},
tooltips: {
},
onClick: function(evt, element) {
if (element.length > 0) {
console.log(element);
// you can also get dataset of your selected element
data.datasets[element[0]._datasetIndex].data[element[0]._index];
}
}
};
All you need to do is just add onClick callback in graph options property
options={{
.....
onClick: function(evt, element) {
if(element.length > 0) {
console.log(element,element[0]._datasetInde)
// you can also get dataset of your selected element
console.log(data.datasets[element[0]._datasetIndex])
}
}}
You need to get ref, and add event getElementAtEvent.
import { Bar } from 'react-chartjs-2'
import { Chart } from 'chart.js'
const BarChart = () => {
const chartRef = useRef<HTMLCanvasElement>(null)
...
return ( <Bar
type='horizontalBar'
data={chartData}
ref={chartRef}
getElementAtEvent={(i: any, event: any) => {
if (chartRef.current) {
const chart = Chart.getChart(chartRef.current)
const clickedElements = chart!.getElementsAtEventForMode(event, 'y',{axis: 'x', intersect: false}, true)
if (clickedElements.length > 0) {
console.log(clickedElements[0].index) // Here clicked label | data index
}
}
}}
options={options}/>
)
}
I am working on a project where I am implementing some charts from the Vue-Chartjs library. I need the Y-axis max value to change everytime the user changes the filters given. I Import an existing barchart from the vue-chartjs library. In the code there is a javascript file that has some defaults already, to set extra options I can use the extraOptions object as a prop to personalize each chart accordingly. Here is the default component:
import { Bar } from 'vue-chartjs'
import { hexToRGB } from "./utils";
import reactiveChartMixin from "./mixins/reactiveChart";
let defaultOptions = {
tooltips: {
tooltipFillColor: "rgba(0,0,0,0.5)",
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
tooltipFontSize: 14,
tooltipFontStyle: "normal",
tooltipFontColor: "#fff",
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
tooltipTitleFontSize: 14,
tooltipTitleFontStyle: "bold",
tooltipTitleFontColor: "#fff",
tooltipYPadding: 6,
tooltipXPadding: 6,
tooltipCaretSize: 8,
tooltipCornerRadius: 6,
tooltipXOffset: 10,
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
fontColor: "#9f9f9f",
fontStyle: "bold",
beginAtZero: true,
display: false,
min: 0,
max: 100
},
gridLines: {
display: false,
drawBorder: false,
}
}],
xAxes: [{
gridLines: {
display: false,
drawBorder: false,
},
}],
}
};
export default {
name: 'BarChart',
extends: Bar,
mixins: [reactiveChartMixin],
props: {
labels: {
type: [Object, Array],
description: 'Chart labels. This is overridden when `data` is provided'
},
datasets: {
type: [Object, Array],
description: 'Chart datasets. This is overridden when `data` is provided'
},
data: {
type: [Object, Array],
description: 'Chart.js chart data (overrides all default data)'
},
color: {
type: String,
description: 'Chart color. This is overridden when `data` is provided'
},
extraOptions: {
type: Object,
description: 'Chart.js options'
},
title: {
type: String,
description: 'Chart title'
},
},
methods: {
assignChartData() {
let { gradientFill } = this.assignChartOptions(defaultOptions);
let color = this.color || this.fallBackColor;
return {
labels: this.labels || [],
datasets: this.datasets ? this.datasets : [{
label: this.title || '',
backgroundColor: gradientFill,
borderColor: color,
pointBorderColor: "#FFF",
pointBackgroundColor: color,
pointBorderWidth: 2,
pointHoverRadius: 4,
pointHoverBorderWidth: 1,
pointRadius: 4,
fill: true,
borderWidth: 1,
data: this.data || []
}]
}
},
assignChartOptions(initialConfig) {
let color = this.color || this.fallBackColor;
const ctx = document.getElementById(this.chartId).getContext('2d');
const gradientFill = ctx.createLinearGradient(0, 170, 0, 50);
gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)");
gradientFill.addColorStop(1, hexToRGB(color, 0.6));
let extraOptions = this.extraOptions || {}
return {
...initialConfig,
...extraOptions,
gradientFill
};
}
},
mounted() {
this.chartData = this.assignChartData({});
this.options = this.assignChartOptions(defaultOptions);
this.renderChart(this.chartData, this.options, this.extraOptions);
}
}
I use this js file to import the bar chart inside a vue component like you see down below.
everytime the input of the form changes i need to re render the chart. I use the onInputChange() method to turn the boolean loaded to false and call the loadData() method.
Inside the loadData() method I make an axios request that gets me the right data every time. I also get the maximum value for my Y axis.
Then in the response I call on updateChart() so that I can update the data and the max value of the chart. then i turn the boolean loaded to true again so that my chart renders accordingly.
The problem with this approach is that the chart disappears completely for a split of a second. Before deciding to change the max Value of the Y axis I was able to update the data of my chart without having to use the v-if="loaded".
I need to find a solution where the chart re renders without it completely disappearing from the page. I know some suggested to use computed variables but i don't fully understand how it is supposed to work. Here is the component minus the form fields.
I guess in it's essence what I want is to update the Y axis max value without having to re render the entire chart.
<template>
<div>
<BarChart v-if="loaded" :labels="chartLabels"
:datasets="datasets"
:height="100"
:extraOptions="extraOptions"
>
</BarChart>
<br>
</div>
</template>
<script>
import BarChart from '../../components/Library/UIComponents/Charts/BarChart'
import Dropdown from "../../components/Library/UIComponents/Dropdown"
import GroupedMultiSelectWidget from "~/components/widgets/GroupedMultiSelectWidget"
import SelectWidget from "../../components/widgets/SelectWidget";
export default{
name: 'PopularChart',
components: {BarChart, Dropdown, SelectWidget, GroupedMultiSelectWidget},
data(){
return {
loaded:true,
form:{
day: 'Today',
workspace:'',
machine_family: [],
duration: [],
user_group: [],
dt_start:'',
dt_end:''
},
url: `/api/data_app/job_count_by_hour/`,
chart_data: [],
days: [ {day:"Today", id:"Today"},
{day:"Monday", id:"0"},
{day:"Tuesday",id:"1"},
{day:"Wednesday",id:"2"},
{day:"Thursday",id:"3"},
{day:"Friday",id:"4"},
{day:"Saturday",id:"5"},
{day:"sunday",id:"6"} ],
chartLabels: ["00u", "1u", "2u", "3u","4u","5u", "6u", "7u", "8u", "9u", "10u", "11u", "12u", "13u", "14u", "15u","16u", "17", "18u","19u","20u","21u","22u","23u"],
datasets: [],
maximumValue: '',
extraOptions:{}
}
},
methods: {
onInputChange() {
this.loaded = false
this.loadData()
},
async loadData() {
await this.$axios.get(`${this.url}?day=${this.form.day}&date_start=${this.form.dt_start}&date_end=${this.form.dt_end}&workspace=${this.form.workspace}&user_group=${this.form.user_group}&machine_family=${this.form.machine_family}`)
.then(response => {
this.updateChart(response.data.results,response.data.maximum)
this.loaded = true
})
},
updateChart(data,maxValue) {
this.datasets = [{
label: ["jobs %"],
backgroundColor:"#f93232",
data: data
},]
this.maximumValue = maxValue
this.extraOptions = {
tooltips: {
callbacks:{
label: function (tooltipItems,){
if (tooltipItems.value > ((50/100) * maxValue)){
return 'busy';
}else if (tooltipItems.value < ((30/ 100) * maxValue) ){
return ' not busy';
}else if ( tooltipItems.value < ((40/ 100) * maxValue )){
return 'kind of busy'
}
}
}
},
scales: {
yAxes: [{
gridLines: {
zeroLineColor: "transparent",
display: false,
drawBorder: false,
},
ticks: {
max: this.maximumValue,
display: true,
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent",
display: false,
drawBorder: false,
},
}],
},
}
},
},
mounted() {
this.loadData()
},
}
</script>
After checking your code, I noticed that you are using the datasets and maximumValue in data function.
To update the chart data based on dataset and maximumValue, you need to use those variables in computed data, not data.
For example,
computed: {
chartData() {
let chartData = {
labels: [],
datasets: [...],
}
return chartData;
},
maximumValue() {
return this.maxValue;
}
},
methods: {
renderBarChart() {
this.renderChart(this.chartData, {
legend: {
display: false,
},
responsive: true,
maintainAspectRatio: false,
options: {
scales: {
yAxes: [{
ticks: {
max: this.maximumValue
}
}],
},
}
});
},
},
I need to apply labels on top of chart following the columns just like the image (the numbers aside the text 'Resultado mês'):
Image of the desired result
Some help please?
The page is bellow (the labels need to go before the legends).
I've provided a HTML/CSS solution temporarily in the page bellow , but I'm waiting for the real solution:
http://www.pdagencia.com.br/porto/pages/10.3%20-%20consultar-dados-bancarios-01_v2.html#tab3
window.onload = function() {
var ctx = document.getElementById('ps-chart').getContext('2d');
var data = {
labels: ["Jan/18", "Fev/18", "Mar/18", "Abr/18", "Mai/18", "Jun/18", "Jul/18", "Ago/18", "Set/18", "Out/18", "Nov/18", "Dez/18"],
datasets: [{
label: "Entradas",
data: [650, 590, 800, 810, 560, 550, 400, 800, 810, 560, 550, 400],
backgroundColor: '#33bfff'
},
{
label: "Saídas",
data: [-280, -480, -400, -190, -860, -270, -900, -400, -190, -860, -270, -900],
backgroundColor: '#E75A5B'
}
]
}
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
responsive: false,
plugins: {
datalabels: {
formatter: function(value, context) {
return context.dataset.data[context.dataIndex].toLocaleString('pt-BR', {
style: 'currency',
currency: 'BRL'
});
}
}
},
legend: {
display: true,
},
tooltips: {
"enabled": false
},
scales: {
yAxes: [{
display: false,
ticks: {
display: false
}
}],
xAxes: [{
stacked: true,
barPercentage: 1.2,
gridLines: {
display: false
}
}]
}
}
});
}
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.7.2/Chart.bundle.min.js"></script>
<script src="https://github.com/chartjs/chartjs-plugin-datalabels/releases/download/v0.3.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="ps-chart" style="width:100%"></canvas>
I am new to the chart js and javascript.
As I have faced the same problem, I wanted to display the sum of two values into the label,
I got some solution for the same as below.
Maybe it can help you.
Check it out:
http://www.chartjs.org/samples/latest/tooltips/callbacks.html
tooltips: {
mode: 'index',
callbacks: {
// Use the footer callback to display the sum of the items
showing in the tooltip
footer: function(tooltipItems, data) {
var sum = 0;
tooltipItems.forEach(function(tooltipItem) {
sum += data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
});
return 'Sum: ' + sum;
},
},
footerFontStyle: 'normal'
},
hover: {
mode: 'index',
intersect: true
},
This is my jsfiddle link http://jsfiddle.net/bb1m6xyk/1/
I want that all my labels like my data: 0 etc are positioned at the base and in center of each zone.
$('#container').highcharts({
chart: {
type: 'area'
},
yAxis: {
title: {
text: 'Percent'
}
},
plotOptions: {
area: {
enableMouseTracking: false,
showInLegend: false,
stacking: 'percent',
lineWidth: 0,
marker: {
enabled: false
},
dataLabels: {
className:'highlight',
enabled: true,
formatter: function () {
console.log(this);
return this.point.myData
}
}
}
},
series: [{
name: 'over',
color: 'none',
data: overData
}, {
id: 's1',
name: 'Series 1',
data: data,
showInLegend: true,
zoneAxis: 'x',
zones: zones
}]
});
Is this possible? I tried it using className on dataLabels but it doesn't take that into effect.
Any help is appreciated.
There are a few ways to render labels on a chart.
The Renderer
Live example: http://jsfiddle.net/11rj6k6p/
You can use Renderer.label to render the label on the chart - this is a low level approach but it gives you full control how the labels will be rendered. You can loop the zones and set x and y attributes of the labels, e.g. like this:
const labels = ['l1', 'l2', 'l3', 'l4', 'l5']
function drawLabels() {
const zonesLabels = this.zonesLabels
const series = this.get('s1')
const { yAxis, xAxis } = series
const y = yAxis.toPixels(0) - 20 // -20 is an additional offset in px
series.zones.reduce((prev, curr, i) => {
if (curr.value !== undefined) {
const x = (xAxis.toPixels(prev.value) + xAxis.toPixels(curr.value)) / 2
if (!zonesLabels[i]) {
zonesLabels.push(
this.renderer.label(labels[i], x, y).add().attr({
align: 'center',
zIndex: 10
})
)
} else {
zonesLabels[i].attr({ x, y })
}
}
return curr
}, { value: series.dataMin })
}
Then set the function on load - to render the labels, and on redraw - to reposition the labels if the chart size changed.
chart: {
type: 'area',
events: {
load: function() {
this.zonesLabels = []
drawLabels.call(this)
},
redraw: drawLabels
}
},
The annotations module
Live example: http://jsfiddle.net/a5gb7aqz/
If you do not want to use the Renderer API, you can use the annotations module which allows to declare labels in a chart config.
Add the module
<script src="https://code.highcharts.com/modules/annotations.js"></script>
Map zones to the labels config object
const labels = ['l1', 'l2', 'l3', 'l4', 'l5']
function annotationsLabels() {
const zonesLabels = []
zones.reduce((prev, curr, i) => {
zonesLabels.push({
text: labels[i],
point: {
x: (prev.value + curr.value) / 2,
y: 0,
xAxis: 0,
yAxis: 0
}
})
return curr
}, { value: 0 })
return zonesLabels
}
Set the annotations options
annotations: [{
labels: annotationsLabels(),
labelOptions: {
shape: 'rect',
backgroundColor: 'none',
borderColor: 'none',
x: 0,
y: 0
}
}],
Data labels and a new series
Live example: http://jsfiddle.net/wpk1495g/
You can create a new scatter series which will not respond to mouse events and it won't be visible in the legend. The labels can be displayed as data labels.
Map zones to series points
const labels = ['l1', 'l2', 'l3', 'l4', 'l5']
function seriesData() {
const points = []
zones.reduce((prev, curr, i) => {
points.push( {
x: (prev.value + curr.value) / 2,
y: 50,
dataLabels: {
enabled: true,
format: labels[i]
}
})
return curr
}, { value: 0 })
return points
}
Set the series options in the chart config
, {
type: 'scatter',
enableMouseTracking: false,
showInLegend: false,
data: seriesData(),
zIndex: 10,
color: 'none',
dataLabels: { style: { textOutline: false }, x: 0, y: 0 }
}
Output