Nivo not showing any tooltip - nivo-react

I'm trying to mimic the tooltip shown in nivo homepage line graph. My code so far:
<ResponsiveLine
data={data}
margin={{ top: 50, right: 110, bottom: 50, left: 60 }}
xScale={{
format: '%Y-%m-%d',
type: 'time',
precision: 'day',
}}
yScale={{
type: 'linear',
max: 500,
min: 100,
}}
areaBaselineValue={100}
xFormat="time:%Y-%m-%d"
enablePoints={false}
enableGridX={false}
gridYValues={[100, 300, 500]}
useMesh
isInteractive
enableCrosshair
crosshairType="x"
colors={['#4F82CE', '#7BE0B1', '#990620']}
enableArea
enableSlices="x"
axisBottom={{
tickValues: [
new Date(2022, 0, 1),
new Date(2022, 4, 1),
],
format: '%b %d',
}}
axisLeft={null}
axisRight={{
tickValues: [100, 300, 500],
}}
/>
My output
There doesn't seem to be any tooltip showing, but other than providing my own custom tooltip, I wasn't able to find any way of showing it there.

Related

Polar Area Chart with equal sized section

I would like to create an Polar Area Chart with equal size sections (not based on the actual value) like this with ng2-charts: Example
I thought that using the scales.r.max setting at 1 will create the effect I need, but any data that exceeds the max value overflow outside the bound of the chart instead of clipping it.
Does anybody have an idea how to achieve this?
Thanks in advance for your help,
I think you don't need a polar area but a pie chart should fit better the picture you posted.
You could define a data array with all the same value "1 / labels.length" where labels are the months of the posted picture.
Then you should use Datalabels plugin in order to set the real number to show in the chart.
const labels = ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'];
const data = [65, 8, 90, 81, 56, 55, 40];
const value = 1 / labels.length;
const colors = [
'rgb(53, 152, 219)',
'rgb(46, 204, 113)',
'rgb(155, 89, 182)',
'rgb(241, 196, 15)',
'rgb(189, 195, 199)',
'rgb(203, 184, 214)',
'rgb(216, 252, 207)'
];
const ctx = document.getElementById("myChart");
const polarChart = new Chart(ctx, {
type: 'pie',
plugins: [ChartDataLabels],
data: {
labels: labels,
datasets: [{
data: labels.concat().fill(value),
backgroundColor: colors,
}]
},
options: {
plugins: {
legend: {
position: 'right'
},
datalabels: {
color: 'black',
font: {
size: 24,
weight: 'bold'
},
formatter: (value, context) => data[context.dataIndex]
}
},
}
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.1.0/dist/chartjs-plugin-datalabels.min.js"></script>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"></canvas>
</div>

I am not able to remove legend in this google chart, also not able to change height , I putted it inside a col-md-4 div , also there help me

js code :
its to add chart to col-4 bar must have 3 columns each having space between it all different color, remove legend in this google chart
function drawBarChart() {
var data = google.visualization.arrayToDataTable([
["Retention", "Level", {
role: "style"
}],
["HIGH", 12, "#E54B4B"],
["ELEVATED", 29, "#FFB100"],
["LOW", 52, "#2BC18D"],
]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
height: 600,
width: 370,
legend: 'none',
bar: {
groupWidth: "55%"
},
ticks: [0, 20, 40, 60, 80, 100],
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_divTwo'));
// Convert the Classic options to Material options.
chart.draw(data, google.charts.Bar.convertOptions(data, options));
};

trying to get minIndex and maxIndex from x-axis-0

I'm attempting to capture data as shown in this question Chart.js get array of currently visible points on graph and am getting most of the way there. However, in inspecting the properties of my x-axis-0, I'm not locating minIndex or maxIndex as detailed in the thread. I do have max and min properties, but those do not appear to work for slicing, as far as my attempts have gone. Curious if those more expert in chartjs can help me figure out the minIndex and maxIndex variables.
editing for more detail:
So I think maybe the issue is that in the link provided, the example is using categorical data and in my own example I have the xaxis as time data? I tried jsfiddle and I see minIndex and maxIndex on the category type whereas I don't see those in my time type axis.
I see the following when I do a console log of the x-axis-0
n {id: "x-axis-0", type: "time", options: {…}, ctx:
CanvasRenderingContext2D, chart: en, …}
bottom: 475
chart: en {id: 0, ctx: CanvasRenderingContext2D, canvas: canvas#myChart.chartjs-render-monitor, config: {…}, width: 1110, …}
ctx: CanvasRenderingContext2D {canvas: canvas#myChart.chartjs-render-monitor, globalAlpha: 1, globalCompositeOperation: "source-over", filter: "none", imageSmoothingEnabled: true, …}
fullWidth: false
height: 15.76
hidden: false
id: "x-axis-0"
labelRotation: 0
left: 35.781484375
longestLabelWidth: 0
longestTextCache: {normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif: {…}}
margins: {left: 35.781484375, right: 3, top: 0, bottom: 0}
max: 1614922685400.2363
maxHeight: 237.5
maxWidth: 1074.218515625
min: 1614922568591.0784
minSize: {width: 1074.218515625, height: 15.76}
options: {display: true, position: "bottom", offset: false, gridLines: {…}, scaleLabel: {…}, …}
paddingBottom: 0
paddingLeft: 3
paddingRight: 3
paddingTop: 0
position: "bottom"
right: 1107
ticks: []
top: 459.24
type: "time"
weight: 0
width: 1071.218515625
_adapter: rn {options: {…}}
_endPixel: 1107
_gridLineItems: [ticksLength: 0, borderValue: 459.5]
_labelItems: []
_labelSizes: {first: {…}, last: {…}, widest: {…}, highest: {…}}
_layers: ƒ ()
_length: 1071.218515625
_majorUnit: undefined
_maxLabelLines: 0
_offsets: {start: 0, end: 0, factor: 1}
_reversePixels: false
_startPixel: 35.781484375
_table: (2) [{…}, {…}]
_ticks: []
_ticksToDraw: []
_timestamps: {data: Array(3601), datasets: Array(2), labels: Array(3616)}
_unit: "hour"
__proto__: n
edit 2:
I created a jfiddle for this https://jsfiddle.net/d489uesh/ Just for experimenting I did a console log for the value of minIndex and it appears to only be 0 or 1, and it does not work at all if I use time as the type of axis. The end goal of all of this is to use the array of retrieved y-values to calculate an average for the drag highlight zoom selection, I feel like I'm so close, so appreciate any assistance!
As you have mentioned, console log of the x-axis-0 does not have the min and max index. I was working in a project that requires almost identical solution to yours hence had to find a way around.
I added the moment.min.js and added time type to x-axis because drag zoom doesn't seem to work without it:
type: 'time',
time: { parser: 'HH:mm:ss', displayFormats: { second: "HH:mm:ss" } },
I got the first and last value from chart.scales["x-axis-0"].ticks after zoom and got the desired min and max index from chart.data.labels and the rest was easy.
var data = chart.data.labels;
var l = chart.scales["x-axis-0"].ticks;
l = l.length -1;
var min = data.indexOf(chart.scales["x-axis-0"].ticks[0]);
var max = data.indexOf(chart.scales["x-axis-0"].ticks[l]);
document.getElementById("vv").innerText = JSON.stringify(chart.data.datasets[0].data.slice(min, max +1));
Here is the jsfiddle:
https://jsfiddle.net/ModeNashid/84zuqwLa/3/
Note that I did not check the versions of any of the resources that you have included in your jsfiddle so there might be some warnings.

Chartjs 2: Multi level/hierarchical category axis in chartjs

Is it possible to define a bar chart with a multi level/category axis?
For instance I'd like to display the Region/Province categories like in this Excel chart:
I found this example using multiple xAxes.
xAxes:[
{
id:'xAxis1',
type:"category",
ticks:{
callback:function(label){
var month = label.split(";")[0];
var year = label.split(";")[1];
return month;
}
}
},
{
id:'xAxis2',
type:"category",
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
ticks:{
callback:function(label){
var month = label.split(";")[0];
var year = label.split(";")[1];
if(month === "February"){
return year;
}else{
return "";
}
}
}
}
]
The problem is it seems that the two axes are not really linked and the alignment of second axis is based on values instead of aligning in middle of lower level category. this case cause issues
Is there a clean way to achieve this in chart.js?
Update:
I ended up creating a feature request on chartjs.
you can provide value separately for different axis via datesets and provide an object with different configuration option (borderColor, pointBackgroundColor, pointBorderColor) etc, i hope It'll help.
here is the link for the with an update (fiddle you shared) Updated Fiddle
data: {
labels: ["January;2015", "February;2015", "March;2015", "January;2016", "February;2016", "March;2016"],
datasets: [{
label: '# of Votes',
xAxisID:'xAxis1',
data: [12, 19, 3, 5, 2, 3]
},
// here i added another data sets for xAxisID 2 and it works just fine
{
label: '# of Potatoes',
xAxisID:'xAxis2',
data: [9, 17, 28, 26, 29, 9]
}]
}
I hope that solves your problem :)
Hope this helps,
I did a bit of research and couldn't find methods to implement your solution in chartjs. Chartjs has grouped bar charts but not subgrouped bar charts like in your case.
Example: http://jsfiddle.net/harshakj89/ax3zxtzw/
Here are some alternatives,
D3js (https://d3js.org/) can be used to create sub grouped bar charts.Data can be loaded from csv or json. D3 is highly configurable, but you may have to put some effort than chartsjs.
https://plnkr.co/edit/qGZ1YuyFZnVtp04bqZki?p=preview
https://stackoverflow.com/questions/37690018/d3-nested-grouped-bar-chart
https://stackoverflow.com/questions/15764698/loading-d3-js-data-from-a-simple-json-string
ZingChart is a commercial tool and can be used to implement bar charts with sub groupes.
https://www.zingchart.com/docs/chart-types/bar-charts/
But I prefer D3 over this library. because D3 comes under BSD License.
This should work as per your requirement http://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/#8-grouped-bar-chart
The best library I could found to have exactly this feature is Highcharts, this is my implementation:
and here http://jsfiddle.net/fieldsure/Lr5sjh5x/2/ you can find out how to implement it.
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: "container",
type: "column",
borderWidth: 5,
borderColor: '#e8eaeb',
borderRadius: 0,
backgroundColor: '#f7f7f7'
},
title: {
style: {
'fontSize': '1em'
},
useHTML: true,
x: -27,
y: 8,
text: '<span class="chart-title"> Grouped Categories with 2 Series<span class="chart-href"> Black Label </span> <span class="chart-subtitle">plugin by </span></span>'
},
yAxis: [{ // Primary yAxis
labels: {
format: '${value}',
style: {
color: Highcharts.getOptions().colors[0]
}
},
title: {
text: 'Daily Tickets',
style: {
color: Highcharts.getOptions().colors[0]
}
}
}, { // Secondary yAxis
title: {
text: 'Invoices',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '${value}',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}]
,
series: [{
name: 'Daily',
type: 'column',
yAxis: 1,
data: [4, 14, 18, 5, 6, 5, 14, 15, 18],
tooltip: {
valueSuffix: ' mm'
}
}, {
name: 'Invoices',
type: 'column',
data: [4, 17, 18, 8, 9, 5, 13, 15, 18],
tooltip: {
valueSuffix: ' °C'
}
}],
xAxis: {
categories: [{
name: "1/1/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}, {
name: "1/2/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}, {
name: "1/3/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}]
}
});
});
body {
padding: 0px !important;
margin: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://blacklabel.github.io/grouped_categories/grouped-categories.js"></script>
<div id="container" class="chart-container"></div>
But the problem is the library is not free for commercial purposes, and this is the Chartjs implementation, in my case it is look like this:
const data ={"labels":[{"label":"Exams","children":["Wellness Examination"]},{"label":"Surgery","children":["Neuter Surgery"]},{"label":"Vaccines","children":["Bordetella"]},{"label":"Dentistry","children":["Dental Cleaning"]},{"label":"Diagnostics","children":["Other","Pre-Anesthetic","Adult Diagnostics","Pre-Anesthetic Diagnostics","Heartworm & Tick Borne Disease Test"]},{"label":"Treatments/Other","children":["Other","Microchip"]}],"datasets":[{"label":"Consumed","backgroundColor":"red","tree":[{"value":0,"children":["0"]},{"value":0,"children":["0"]},{"value":1,"children":["1"]},{"value":0,"children":["0"]},{"value":15,"children":["0","1","3","11","0"]},{"value":15,"children":["2","13"]}]},{"label":"Purchased","backgroundColor":"blue","tree":[{"value":28,"children":["28"]},{"value":1,"children":["1"]},{"value":24,"children":["24"]},{"value":10,"children":["10"]},{"value":103,"children":["2","16","34","49","2"]},{"value":165,"children":["75","90"]}]}]};
window.onload = () => {
const ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Hierarchical Bar Chart'
},
layout: {
padding: {
// add more space at the bottom for the hierarchy
bottom: 45
}
},
scales: {
xAxes: [{
type: 'hierarchical',
stacked: false,
// offset settings, for centering the categorical
//axis in the bar chart case
offset: true,
// grid line settings
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
stacked: false,
ticks: {
beginAtZero: true
}
}]
}
}
});
};
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/chart.js/dist/Chart.bundle.js"></script>
<script src="https://unpkg.com/chartjs-scale-hierarchical"></script>
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
for each more column just add another dataset.

google visualization bar chart stacking two bars

I have a google visualization bar chart sample here where the data format is as given below.
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
How to make expenses and profits bar stacked where as sales is a separate bar?
At the moment the Google Charts API doesn't have this in built feature, but with some remodeling of the DataTable and Chart Options you can still achieve this.
My Solution
The Stacked Bar should contain values of only Expenses and Profit, to avoid a Stacked bar with Sales the value in the data column for Sales is represented as zero. A separate Sales bar is created by having a similar data row, but with the value of Sales present, and the rest zero. The Date data type needs to be specified in order to group all bar charts with the same date, if this isn't implemented, then there will be a gap between each bar chart with the same year.
More information on Date representation of Columns is available here.
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'year', type: 'date'},
{label: 'Sales', id: 'Sales', type: 'number'},
{label: 'Expenses', id: 'Expenses', type: 'number'},
{label: 'Profit', id: 'Profit', type: 'number'}],
[{v:new Date('2014'), f:'2014'}, 0, 400, 200],
[{v:new Date('2014'), f:'2014'}, 1000, 0, 0],
[{v:new Date('2015'), f:'2015'}, 0, 460, 250],
[{v:new Date('2015'), f:'2015'}, 1170, 0, 0],
[{v:new Date('2016'), f:'2016'}, 0, 1120, 300],
[{v:new Date('2016'), f:'2016'}, 600, 0, 0],
[{v:new Date('2017'), f:'2017'}, 0, 540, 350],
[{v:new Date('2017'), f:'2017'}, 1030, 0, 0]
]);
To achieve the stacked bar, the google charts configuration option isStacked: true is used. To avoid the vertical axis acting like a timeline with months and days, the vertical axis is formatted to display the Year using vAxis: {format: 'yyyy'}. More information on formatting is available here. To avoid spacing between different Year Bars, the feature bar: {groupWidth: '90%'} is used.
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
},
bars: 'horizontal', // Required for Material Bar Charts.
hAxis: {format: 'decimal'},
vAxis: {
format: 'yyyy'
},
height: 400,
colors: ['#1b9e77', '#d95f02', '#7570b3'],
isStacked: true,
bar: {groupWidth: '90%'}
};