Chart.js Chart does not start at - javascript

I want to that the Chart start at 0. But it takes always the lower value to start.
I already tried a few things but nothing works.
It never takes the settings done in de options Part of de javascript part. So i dont know what the issue is. It never starts at 0. But this is what i want to.
Please help. Thank you very much :)
Looks currently like this: https://school.luis-luescher.com/m242/moin/index.php
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<style type="text/css">
BODY {
width: 550PX;
}
#chart-container {
width: 100%;
height: auto;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
</head>
<body>
<div id="chart-container">
<canvas id="graphCanvas"></canvas>
</div>
<script>
$(document).ready(function() {
showGraph();
});
function showGraph() {
{
$.post("https://school.luis-luescher.com/m242/moin/data.php",
function(data) {
console.log(data);
var trytime = [];
var count = [];
for (var i in data) {
trytime.push(data[i].trytime);
count.push(data[i].count);
}
var chartdata = {
labels: trytime,
datasets: [{
label: 'Erfolgreiche Authentifizerungen',
backgroundColor: '#8846f1',
borderColor: '#a446f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
borderWidth: 1,
data: count,
}],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata
});
});
}
}
</script>
</body>
</html>

Your Options object must be outside chartData.
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
options: options
});

Related

Echarts: When [large: true] is enabled, the tooltip box will disappear when appenddata is dynamically updated

env
echarts version : 5.3.2
os: win11
issue
When using appenddata to update data, and the data volume exceeds the largethreshold, the tooltip will disappear when updating data, and the MouseMove of ecarts will pause for a moment
properties:
series: [
{
large:true,
largeThreshold:200
}
]
When the data point exceeds 200, the tooltip will disappear at [appenddata],
appendData code
myChart.appendData({
seriesIndex: 0,
data:[[Math.random()*12.2,Math.random()*12.4]]
}
);
myChart.resize();
The complete code is as follows
<!DOCTYPE html>
<html lang="zh-CN" style="height: 100%">
<head>
<meta charset="utf-8">
</head>
<body style="height: 100%; margin: 0">
<div id="container" style="height: 100%"></div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts#5.3.2/dist/echarts.min.js"></script>
<script type="text/javascript">
var dom = document.getElementById('container');
var myChart = echarts.init(dom, null, {
renderer: 'canvas',
useDirtyRect: false
});
var option;
function getData() {
let temp = [];
for (let i = 0; i < 100000; i++) {
temp.push([
Math.random()*12.2,Math.random()*12.4
]);
}
return temp;
}
option = {
animation:false,
xAxis: {},
yAxis: {},
dataZoom:[
{
type: 'inside',
xAxisIndex: 0,
}
],
tooltip:{
annotation:false,
trigger: 'item'
},
series: [
{
type: 'scatter',
animation:false,
large:true,
largeThreshold:200,
progressive:1000000,
data: getData()
}
]
};
if (option && typeof option === 'object') {
myChart.setOption(option);
setInterval(()=>{
//appendData 时, toolTip框会消失
//When appendData, the toolTip box will disappear
myChart.appendData({
seriesIndex: 0,
data:[[Math.random()*12.2,Math.random()*12.4]]
}
);
myChart.resize();
},500)
myChart.on('mousemove', function(params) {
// 当appendData 时, 事件会停止一瞬间
// When appendData, the event stops for a moment
console.log("mousemove");
});
}
window.addEventListener('resize', myChart.resize);
</script>
</body>
</html>
Current issues
Expected effect

Code doesn't work after updating chart.js versioning

I have this great code working here where I load the data in from an external file called test.csv.
Everything works great until I try to update the chart.js library link.
Can anyone tell me why this code doesn't work with more current versions of chart.js?
I want to update it so that I can install the plugin that lets you show the charts values. Alternatively some code that would facilitate this would work great as well!
Appreciate any help!
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Data project</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<div class="wrapper">
<h1>MY CHART</h1>
<h2>This is the subhead for my chart </h2>
<canvas id="myChart" width="350" height="250" style="background-color:white;"></canvas>
</div>
<script>
window.addEventListener('load', setup);
async function setup() {
var ctx = document.getElementById('myChart').getContext('2d');
var dollar = await getData();
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: dollar.years,
datasets: [
{
label: 'Voter support (%)',
data: dollar.vals,
backgroundColor: [
'#134D85',
'#134D85',
'#134D85',
'#134D85',
'#134D85',
],
}]
},
options: {
layout: {
padding: {
left: 0,
right: 0,
top: 8,
bottom: 0
}
},
responsive: true,
title: {
display: false
},
legend: {
display: true,
position: 'top',
usePointStyle: true,
padding: 1,
labels: {
boxWidth: 15,
}
},
scales: {
yAxes: [{
gridlines: {
display: true,
color: '#ffffff',
zeroLineColor: '#ffffff',
}
}],
xAxes: [{
gridLines: {
display: true,
drawOnChartArea: false
},
}],
}
}
});
}
async function getData() {
// const response = await fetch('testdata.csv');
var response = await fetch('data/test.csv');
var data = await response.text();
data = data.replace(/"/g, "");
var years = [];
var vals = [];
var rows = data.split('\n').slice(1);
rows = rows.slice(0, rows.length - 1);
rows = rows.filter(row => row.length !== 0)
rows.forEach(row => {
var cols = row.split(",");
years.push(cols[0]);
vals.push(0 + parseFloat(cols[1]));
});
console.log(years, vals);
return { years, vals };
}
</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Coding Train: Data and APIs Project 1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<div class="wrapper">
<h1>MY CHART</h1>
<h2>This is the subhead for my chart </h2>
<canvas id="myChart" width="350" height="250" style="background-color:white;"></canvas>
</div>
<script>
// Data from: https://data.giss.nasa.gov/gistemp/
// Mean from: https://earthobservatory.nasa.gov/world-of-change/DecadalTemp
window.addEventListener('load', setup);
async function setup() {
var ctx = document.getElementById('myChart').getContext('2d');
var dollar = await getData();
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: dollar.years,
datasets: [
{
label: 'Voter support (%)',
data: dollar.vals,
backgroundColor: [
'#134D85',
'#134D85',
'#134D85',
'#134D85',
'#134D85',
],
}]
},
options: {
layout: {
padding: {
left: 0,
right: 0,
top: 8,
bottom: 0
}
},
responsive: true,
title: {
display: false
},
legend: {
display: true,
position: 'top',
usePointStyle: true,
padding: 1,
labels: {
boxWidth: 15,
}
},
scales: {
yAxes: [{
gridlines: {
display: true,
color: '#ffffff',
zeroLineColor: '#ffffff',
}
}],
xAxes: [{
gridLines: {
display: true,
drawOnChartArea: false
},
}],
}
}
});
}
async function getData() {
// const response = await fetch('testdata.csv');
var response = await fetch('data/test.csv');
var data = await response.text();
data = data.replace(/"/g, "");
var years = [];
var vals = [];
var rows = data.split('\n').slice(1);
rows = rows.slice(0, rows.length - 1);
rows = rows.filter(row => row.length !== 0)
rows.forEach(row => {
var cols = row.split(",");
years.push(cols[0]);
vals.push(0 + parseFloat(cols[1]));
});
console.log(years, vals);
return { years, vals };
}
</script>
</body>
</html>```
For a start next time might be a good idea to read the documentation and the migration guide.
Few things that are at least wrong:
Link name has changed to lower case so 2.9.4/Chart.js -> 3.5.0/chart.js
Scales have changed from 2 arrays to objects for each scale:
options: {
scales: {
x: {
// config for default x scale
},
x2: {
// config for second x scale
},
y: {
// config for default y scale
},
}
}
title and legend config have been moved to the plugins section so options.title -> options.plugins.title and options.legend -> options.plugins.legend.
Alternativly you could also just use an older release of the datalabels plugin that has been written for V2
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/1.0.0/chartjs-plugin-datalabels.js"></script>

Adding Context to Django View Causing My Highcharts Map to Disappear

This is my first Django project, and I am working on a Django html template that should contain a Chart.JS bar graph (https://www.chartjs.org/docs/latest/charts/bar.html) alongside a Highcharts drilldown map of the US (https://www.highcharts.com/demo/maps/map-drilldown).
I've successfully implemented my Chart.JS bar graph and passed data to it from our AWS RDS. But now when I try to implement even just the stock Highcharts code from their website, the map fails to render at all. After trying to isolate the problem, I've found that the map does render if I simply delete "context" from the return statement in my view (i.e. delete "context" from the final line in my first block of code below). But this obviously then inhibits my bar graph from rendering. I think I must be missing something with how the highcharts data is loaded in the presence of other context data, but I've been unable to fix it such that both the graph and map render. Any help would be greatly appreciated!
My Django View:
def index(request):
mydb = mysql.connector.connect(
host=xxxx,
user=xxxx,
password=xxxx,
database=xxxx
)
mycursor = mydb.cursor()
mycursor.execute("WITH CS1 AS (SELECT cts.Name, cts.State, m.Frequently, m.Always FROM Masks m JOIN Counties cts ON (m.FIPS = cts.FIPS)) SELECT CS1.State, AVG((CS1.Frequently+CS1.Always)*100) AS Perc_High_Frequency FROM CS1 WHERE CS1.State<>'Puerto Rico' GROUP BY CS1.State ORDER BY Perc_High_Frequency DESC")
tempList = mycursor.fetchall()
statesMaskName = [item[0] for item in tempList]
statesMaskPerc = [item[1] for item in tempList]
context={'statesMaskName':statesMaskName, 'statesMaskPerc':statesMaskPerc}
return render(request,'index.html', context)
The relevant HTML/JS:
<html lang="en" dir="ltr">
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="fixed-header">
<h1>COVID-19 Sentiment and Mask Practices</h1>
</div>
<div>
<div class="col-lg-3" style="float: left; max-height: 6500px;max-width:400px;overflow: scroll; overflow-x:hidden;">
<div style="background-color: #17202A;">
<span style="color: #F7F9F9; text-align: center;"><h4>% Population Who "Frequently" or "Always" Wear Masks When In Public Within 6" of Others (as of July 2-14, 2020)</h4></span>
</div>
<div class="col-lg-12">
<form method="post" enctype="multipart/form-data" action="selectState">
{% csrf_token %}
<div class="col-lg-4" style="float: left; max-height: 3000px;">
<br><br style="line-height: 15px"/>
{% for state in statesMaskName %}
<table style="border-width: 2px; border: #333;">
<tr>
<input type="submit" value="{{state}}" name="statesMaskName" style="width:130px;">
</tr>
</table>
{% endfor%}
</div>
<div style="float: left;">
<canvas id="myChart" height="1360" width="250"></canvas>
</div>
</form>
</div>
</div>
<div class="col-lg-6">
</div>
<div class="col-lg-3">
</div>
</div>
<br>
</body>
<!--my updated code for chartjs graph-->
<script>
const labels = {{statesMaskName|safe}};
const data = {
labels: labels,
datasets: [{
label: '% Population',
color: 'orange',
backgroundColor: 'orange',
borderColor: 'orange',
data: {{statesMaskPerc|safe}},
}]
};
const config = {
type: 'bar',
data,
options: {
indexAxis: 'y',
color: 'white',
scales: {
y: {
grid: {
color: '#b3b1ad',
},
ticks: {
color: 'white',
},
display: false
},
x: {
grid: {
color: '#b3b1ad',
},
ticks: {
color: 'white',
// Include a % sign in the ticks
callback: function(value, index, values) {
return value + '%';
}
}
}
}
}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
<!--stock code for highcharts map-->
<div id="usMap" style="height: 500px; min-width: 310px; max-width: 800px; margin: 0 auto"></div>
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/data.js"></script>
<script src="https://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="https://code.highcharts.com/maps/modules/exporting.js"></script>
<script src="https://code.highcharts.com/maps/modules/offline-exporting.js"></script>
<script src="https://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<script type="text/javascript">
/*
TODO:
- Check data labels after drilling. Label rank? New positions?
*/
let data = Highcharts.geojson(Highcharts.maps['countries/us/us-all']);
const separators = Highcharts.geojson(Highcharts.maps['countries/us/us-all'], 'mapline');
// Set drilldown pointers
data.forEach((d, i) => {
d.drilldown = d.properties['hc-key'];
d.value = i; // Non-random bogus data
});
function getScript(url, cb) {
const script = document.createElement('script');
script.src = url;
script.onload = cb;
document.head.appendChild(script);
}
// Instantiate the map
Highcharts.mapChart('usMap', {
chart: {
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
const chart = this,
mapKey = 'countries/us/' + e.point.drilldown + '-all';
// Handle error, the timeout is cleared on success
let fail = setTimeout(() => {
if (!Highcharts.maps[mapKey]) {
chart.showLoading('<i class="icon-frown"></i> Failed loading ' + e.point.name);
fail = setTimeout(() => {
chart.hideLoading();
}, 1000);
}
}, 3000);
// Show the spinner
chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>'); // Font Awesome spinner
// Load the drilldown map
getScript('https://code.highcharts.com/mapdata/' + mapKey + '.js', () => {
data = Highcharts.geojson(Highcharts.maps[mapKey]);
// Set a non-random bogus value
data.forEach((d, i) => {
d.value = i;
});
// Hide loading and add series
chart.hideLoading();
clearTimeout(fail);
chart.addSeriesAsDrilldown(e.point, {
name: e.point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
});
}
this.setTitle(null, { text: e.point.name });
},
drillup: function () {
this.setTitle(null, { text: '' });
}
}
},
title: {
text: 'Highcharts Map Drilldown'
},
subtitle: {
text: '',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
series: [{
data: data,
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}, {
type: 'mapline',
data: separators,
color: 'silver',
enableMouseTracking: false,
animation: {
duration: 500
}
}],
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
}
});
</script>
</html>

Is it possible to use mouseenter and mouseleave event in chart js?

Right now I'm using onHover into each pie to add some scale/zoom, but I want to use mouseenter and mouseleave. So on mouseenter on each pie it will add some scale/zoom, and on mouseleave, I want it back to its original state.
either mouseenter-mouseleave or mouseover-mouseout is fine.
here is the codepen:
https://codepen.io/graydirt/pen/NWNZNyQ
Thanks guys!
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: '# of Votes',
data: [12, 19, 20],
backgroundColor: [
'red',
'blue',
'green'
],
datalabels: {
color: '#000'
}
}]
},
options: {
legend: {
display: false
},
layout: {
padding: 5
},
onHover: function (evt, elements) {
let segment;
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 5;
} else {
if (segment) {
segment._model.outerRadius -= 5;
}
segment = null;
}
}
}
});
.chart-pie {
width: 400px;
height: 400px;
margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script>
<div class="container p-4">
<div class="chart-pie position-relative">
<canvas id="chartPie"></canvas>
</div>
</div>
Your code is already designed to return to the original size on mouseout, but you have a subtle bug.
You need to define the segment variable outside the chart. With a saved reference to the segment, the mouseout event will fire and the onHover handler will return the pie to its original size.
Please see the attached example below:
let segment;
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: '# of Votes',
data: [12, 19, 20],
backgroundColor: [
'red',
'blue',
'green'
],
datalabels: {
color: '#000'
}
}]
},
options: {
legend: {
display: false
},
layout: {
padding: 5
},
onHover: function(evt, elements) {
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 5;
} else {
if (segment) {
segment._model.outerRadius -= 5;
}
segment = null;
}
}
}
});
.chart-pie {
width: 400px;
height: 400px;
margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script>
<div class="container p-4">
<div class="chart-pie position-relative">
<canvas id="chartPie"></canvas>
</div>
</div>

Line formatting in Chart.js for vertical steps

I have a large data set which, when graphed have several vertical sections as shown below. Chart.js formats these sections with thin, semi-transparent coloring. I want to format these to match the regular, thicker and solid line style.
The dataset itself is normally in a separate file called data.js, but I linked a portion of it from a CodePen.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<!--
NOT USED FOR THIS EXAMPLE
<script src="data.js"></script>
-->
<script src="https://codepen.io/EtherealBug/pen/wjOdoa.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
</body>
<style>
canvas {
width: 100% !important;
max-width: 2000px;
height: auto !important;
}
</style>
<script>
var labels = jsonfile.jsonarray.map(function(e) {
return e.Time;
});
var data = jsonfile.jsonarray.map(function(e) {
return e.Speed;
});
var ctx = myChart.getContext('2d');
var config = {
options: {
legend: {
position: 'bottom',
},
scales: {
xAxes: [{
scaleLabel: {
fontSize: 12,
fontStyle: 'bold',
display: true,
labelString: 'Y(1)'
},
ticks: {
autoSkip: true,
maxTicksLimit: 30,
},
}],
},
},
type: 'line',
data: {
labels: labels,
datasets: [{
fill: false,
label: 'Graph Line',
data: data,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
}]
}
};
var chart = new Chart(ctx, config);
</script>
</html>
I figured it out, what you're seeing when you look at the graph is actually mostly just the individual points. Due to the large number of point data, it wasn't apparent at first, but the lines were thinner than the points width.
The vertical lines being so much thinner are actually because those are formatted with the line settings. By setting the transparency of the points color and border to 0, and by reformatting the line settings, I got was able to format it the way I intended. Sample below for reference should anyone else have a similar issue in the future.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<!--
NOT USED FOR THIS EXAMPLE
<script src="data.js"></script>
-->
<script src="https://codepen.io/EtherealBug/pen/wjOdoa.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
</body>
<style>
canvas {
width: 100% !important;
max-width: 2000px;
height: auto !important;
}
</style>
<script>
var labels = jsonfile.jsonarray.map(function(e) {
return e.Time;
});
var data = jsonfile.jsonarray.map(function(e) {
return e.Speed;
});
var ctx = myChart.getContext('2d');
var config = {
options: {
legend: {
position: 'bottom',
},
scales: {
xAxes: [{
scaleLabel: {
fontSize: 12,
fontStyle: 'bold',
display: true,
labelString: 'Y(1)'
},
ticks: {
autoSkip: true,
maxTicksLimit: 30,
},
}],
},
},
type: 'line',
data: {
labels: labels,
datasets: [{
lineTension: 0.4, //defaul val = 0.4
pointBackgroundColor: 'rgba(0,0,0,0)',
pointBorderColor: 'rgba(0,0,0,0)',
borderColor: 'black',
borderWidth: 4,
fill: false,
label: 'Graph Line',
data: data,
}]
}
};
var chart = new Chart(ctx, config);
</script>
</html>
Note: I'll accept this answer when it allows me in 2 days since it's my own.

Categories