Apexcharts - running in jsfiddle - but not an my PC - javascript

I want to update a chart.
https://jsfiddle.net/q2hLgk9z/2/
the original idea comes from here:https://jsfiddle.net/wxzpk9dn/2/
<head>
<script src="https://cdn.jsdelivr.net/npm/apexcharts#3.18.1/dist/apexcharts.min.js"></script>
</head>
<div>
<input type="radio" id="columnGraph" name="graph" value="line" />
<label for="columnGraph">Line</label>
</div>
<div>
<input type="radio" id="barGraph" name="graph" value="line1" checked />
<label for="barGraph">Barra</label>
</div>
<div id="chartwind" ></div> </pre>
and script
<script>
// CHART OPTIONS by chart type
let chartOptions = {
line1: {
chart: { type: "line" },
series: [
{ name: "One", type: "line", data: [15, 20] },
{ name: "Two", type: "line", data: [30, 25] },
],
labels: ["2017", "2018"],
stroke: { width: 2 },
},
line: {
chart: { type: "line" },
series: [
{ name: "2017", type: "line", data: [65, 20] },
{ name: "2018", type: "line", data: [15, 25] },
],
labels: ["from", "to"],
stroke: { width: 5 },
},
};
//select the radiobuttons
var chartTypeControlButtons = document.querySelectorAll(
'input[type=radio][name="graphicType"]'
),
chartTypeControlButtonInitChecked = document.querySelectorAll(
'input[type=radio][name="graphicType"]:checked'
);
// Chart type changing (HANDLER)
//switch between the graphs
function changeHandler(event) {
let selectedChartType = this.value,
updatedChartOptions = chartOptions[selectedChartType];
chart.updateOptions(updatedChartOptions);
}
//Listener for the radios
Array.prototype.forEach.call(chartTypeControlButtons, function (radio) {
radio.addEventListener("change", changeHandler);
});
// Render the chart with initial options and then
let initialChartType = chartTypeControlButtonInitChecked[0].value,
// think of it as a preparing the ground
// USE 'bar' as the type. If you choose 'pie' ... you will get glithes
initialChartOptions = {
chart: {
width: 350,
type: "line",
},
series: [],
};
// Create chart with init options
// Note that the link to the chart object is in the GLOBAL scope
var chart = new ApexCharts(
document.getElementById("chartwind"),
initialChartOptions
);
chart.render(); // Firstly, prepare the ground
chart.updateOptions(chartOptions[initialChartType]); // Secondly, draw we want
</script>
<div id="chartwind"></div>
</body>
In Jsfiddle it is working but not an my PC.
I load the apexchartversion as fiddle (3.18.1) - but this does not matter.^It is the same issue with the latest version.
I get 2 errormessages:
in the start: after chart.render:Uncaught (in promise) Error: Element not found (maybe because series ist []. But it does not change with values.
then in the update mode: Uncaught TypeError: Cannot read property 'filter' of undefined
Do you have an idea, what I can try on my machine? (I have the same issue on different browsers).
Maybe you have an idea about the difference to fiddle?

Just define your script file path after your <div id="chartwind"></div>.
It will work.
Example:
index.html
<head>
<script src="https://cdn.jsdelivr.net/npm/apexcharts#3.18.1/dist/apexcharts.min.js"></script>
</head>
<div>
<input type="radio" id="columnGraph" name="graph" value="line" />
<label for="columnGraph">Line</label>
</div>
<div>
<input type="radio" id="barGraph" name="graph" value="line1" checked />
<label for="barGraph">Barra</label>
</div>
<div id="chartwind" ></div>
<script src="./apex.js"></script>
apex.js
let chartOptions = {
line1: {
chart: {
type: "line"
},
series: [{
name: "One",
type: "line",
data: [15, 20]
},
{
name: "Two",
type: "line",
data: [30, 25]
},
],
labels: ["2017", "2018"],
stroke: {
width: 2
},
},
line: {
chart: {
type: "line"
},
series: [{
name: "2017",
type: "line",
data: [65, 20]
},
{
name: "2018",
type: "line",
data: [15, 25]
},
],
labels: ["from", "to"],
stroke: {
width: 5
},
},
};
var chartTypeControlButtons = document.querySelectorAll(
'input[type=radio][name="graph"]'
),
chartTypeControlButtonInitChecked = document.querySelectorAll(
'input[type=radio][name="graph"]:checked'
);
//console.log("checked", chartTypeControlButtonInitChecked.length);
//console.log("radios", chartTypeControlButtons.length);
function changeHandler(event) {
let selectedChartType = this.value,
updatedChartOptions = chartOptions[selectedChartType];
//console.log("change");
chart.updateOptions(updatedChartOptions);
}
Array.prototype.forEach.call(chartTypeControlButtons, function(radio) {
radio.addEventListener("change", changeHandler);
});
// Render the chart with initial options and then
// you can update it with ANY wished options
// let initialChartType = $(chartTypeControlButtonInitChecked).val(),
//console.log("text", chartTypeControlButtonInitChecked[0].value);
let initialChartType = chartTypeControlButtonInitChecked[0].value,
// think of it as a preparing the ground
// USE 'bar' as the type. If you choose 'pie' ... you will get glithes
initialChartOptions = {
chart: {
width: 350,
type: "line",
},
labels: ["from", "to"],
stroke: {
width: 2
},
series: [],
};
// Create chart with init options
// Note that the link to the chart object is in the GLOBAL scope
var chart = new ApexCharts(
document.getElementById("chartwind"),
initialChartOptions
);
//console.log("initialChartType", initialChartType);
chart.render(); // Firstly, prepare the ground
//console.log(chartOptions[initialChartType]);
chart.updateOptions(chartOptions[initialChartType]); // Secondly, draw we want
// chart.updateOptions(newOptions); Redraw we want

Related

how to display labels at top of charts(chart.js)

in the below code the labels are appiles (that i can see the label name on hovering over the colors) but not displayed in the top of the chart (this.color->this.value)like,need labels at the top of chart as like below image. help to get those labels.
var p=[22,33,44,55,66];
firebase.firestore().collection("product_info").onSnapshot(
async function(querySnapshot){
querySnapshot.forEach(async function(doc){
var temp=await doc.data().name;
it.push(await temp);
console.log(it);
});
});
console.log(it);
Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#292b2c';
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: it,
datasets: [{
data: p,
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
}
,
});
Add a legend to your config:
{
type: 'pie',
data: {
...
},
options: {
legend: {
position: 'top'
}
}
...
}
Example:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: [ "My", "Dataset", "Labels" ],
datasets: [{
data: [ 22, 33, 44 ],
backgroundColor: [ '#007bff', '#dc3545', '#9932CC' ]
}]
},
options: {
legend: {
position: 'top'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<div class="container">
<div>
<canvas id="myChart"></canvas>
</div>
</div>

bind JSON file to Echarts (JQuery get)

I want to import my JSON file to Echarts to make a line chart but failed, the result page is totally blank. I search it in google but couldn't find a proper answer.
This is the JSON:
[
{ "category": "A", "value": 1 },
{ "category": "B", "value": 2 },
{ "category": "C", "value": 3 },
{ "category": "D", "value": 7 }
]
var dataArr = [];
var myChart = echarts.init(document.getElementById('demo'));
$.get('data.json', {}, function(response) {
dataArr = JSON.parse(response);
initEchart();
});
function initEchart() {
// specify chart configuration item and data
var option = {
title: {
text: 'entry example'
},
tooltip: {},
xAxis: {
type: 'category',
data: dataArr.category
},
yAxis: {},
series: [{
type: 'line',
data: dataArr.value
}]
};
myChart.setOption(option);
}
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" integrity="sha256-eKrx6Ly6b0Rscx/PSm52rJsvK76RJyv18Toswq+OLSs=" crossorigin="anonymous"></script>
<div id="demo" style="width: 600px;height:400px;"></div>
Thank you for helping me solve this problem.
I fixed your version. You tried to pass to the chart empty data because key dataArr.category does not exist. You received array so need collect data with loop: dataArr.map(row => row['category']) and will be ok.
var dataArr = [];
var myChart = echarts.init(document.getElementById('demo'));
$.get('https://gist.githubusercontent.com/creadone/d15105b0c7e33848ef9559c28a9912c2/raw/64a17c5ac38b375cd6ab858d51a66836d9259ed0/data.json', {}, function(response) {
dataArr = JSON.parse(response);
console.log(dataArr);
initEchart();
});
function initEchart() {
// specify chart configuration item and data
var option = {
title: {
text: 'entry example'
},
tooltip: {},
xAxis: {
type: 'category',
data: dataArr.map(row => row['category'])
},
yAxis: {},
series: [{
type: 'line',
data: dataArr.map(row => row['value'])
}]
};
myChart.setOption(option);
}
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" integrity="sha256-eKrx6Ly6b0Rscx/PSm52rJsvK76RJyv18Toswq+OLSs=" crossorigin="anonymous"></script>
<div id="demo" style="width: 600px;height:400px;"></div>

Trying to call API and plot a line chart but it does not show

I am using Chart.js to draw a simple line chart. Everything looks fine, I get data from API but I can't able to show on the line chart :
$.ajax({
url: "https://api.thevirustracker.com/free-api?countryTimeline=PK",
dataType: 'json',
success: function(result) {
const datachart = []
console.log("datachart", datachart)
for (var i = 0, l = result.timelineitems.length; i < l; i++) {
const entries = result.timelineitems[i]
const x = Object.keys(entries);
const y = Object.values(entries)
// const y = [2,2,4,7,5,4,7,4,1,0,7,4,8,5,44,1,44,111,44,1,11,1,77,88,55,22,99,66,55,77,44,55,22,00,44,77,8,9,5,7,4,1]
datachart.push({
y: y,
x: x
})
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
datasets: [{
data: datachart,
label: ["datachart[1]"],
borderColor: "#18bc9c",
fill: false
}]
},
// Configuration options go here
options: {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="myChart" width="200" height="200"></canvas>
I want to add an array of x variable as a label and data is to add Object.values(entries).new_daily_cases as a data to be shown
The data property of individual datasets for a line chart can be passed in two formats, number[] or Point[]. Point[] is useful in the following cases:
If the number of data points from individual datasets is different.
if x-values of data points from different datasets are different.
In your case, if you specify data.labels, there's no need to define the data of individual datasets as an array of Point.
Please have a look at your amended code below:
$.ajax({
url: "https://api.thevirustracker.com/free-api?countryTimeline=PK",
dataType: 'json',
success: result => {
const rawData = result.timelineitems[0];
delete rawData.stat;
const labels = Object.keys(rawData);
const data = Object.values(rawData);
var chart = new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'New Daily Cases',
data: data.map(o => o.new_daily_cases),
borderColor: "violet",
fill: false
},
{
label: 'New Daily Deaths',
data: data.map(o => o.new_daily_deaths),
borderColor: "orange",
fill: false
},
{
label: 'Total Cases',
data: data.map(o => o.total_cases),
borderColor: "blue",
fill: false
},
{
label: 'Total recoveries',
data: data.map(o => o.total_recoveries),
borderColor: "green",
fill: false
},
{
label: 'Total Deaths',
data: data.map(o => o.total_deaths),
borderColor: "red",
fill: false
}]
},
options: {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Highcharts getjson and changing series type dynamically

I wan't to change series type, but
there is an javascript console error:
options.series in function change_chart is null...
<script src="../code/highstock.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
<script type="text/javascript">
var chart;
var options;
$(document).ready(function() {
options = {
chart: { renderTo: 'container'},
rangeSelector: {selected: 1},
title: { text: 'AAPL Stock Price'},
series: [{
type: 'candlestick',
name: 'AAPL Stock Price11',
dataGrouping: {
units: [
[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]
]
}
}]
};
chartfunc = function(type)
{
alert(options.series);
options.type = type;
chart = new Highcharts.stockChart(options);
}
$.getJSON('http://localhost/highstock/data/aapl-ohlcv.json', function(data) {
options.series[0].data = data;
chart = new Highcharts.stockChart(options);
});
});
</script>
I don't understand why options.series "sets itself" to null...
I got it working by changing chartfunc like this:
chartfunc = function(type)
{
chart.series[0].update({
type: type
});
}

chart.js ajax pushing another dataset always "undefined"

Following is my javascript Code, but the only thing really relevant is the last function. I want to update the Chart to add another dataset, without reloading the Page. But for reason the added dataset is always undefined. The commented-out line, which uses the exact same array of data, on the other hand works. Since I'm new to javascript I'm not sure, if I missed something obvious, or if chart.js just doesn't support this kind of thing at all.
const CHART = document.getElementById("lineChart");
var dts1 = [
{
label: "Abfall gesamt",
data: Abfall_gesamt,
}
];
var dts2 = [
{
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
}
];
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: Jahr,
datasets: dts1
}
});
function myFunction(){
//lineChart.data.datasets[0].data = Abfall_schadstoff;
lineChart.data.datasets.push(dts2);
lineChart.update();
}
The issue is, you are defining your datasets (dts1 and dts2) as an array. They should be an object, like so ...
var dts1 = {
label: "Abfall gesamt",
data: Abfall_gesamt,
};
var dts2 = {
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
};
and then, when generating the chart, set datasets value as ...
datasets: [dts1]
ᴅᴇᴍᴏ
const CHART = document.getElementById("lineChart");
var Abfall_gesamt = [1, 2, 3];
var Abfall_schadstoff = [4, 5, 6]
var dts1 = {
label: "Abfall gesamt",
data: Abfall_gesamt,
backgroundColor: 'rgba(255, 0, 0, 0.2)'
};
var dts2 = {
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
backgroundColor: 'rgba(0, 0, 255, 0.2)'
};
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: ['Jahr', 'Mahr', 'Kadr'],
datasets: [dts1]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
}
});
function myFunction() {
//lineChart.data.datasets[0].data = Abfall_schadstoff;
lineChart.data.datasets.push(dts2);
lineChart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button id="add" onclick="myFunction()">Add Dataset</button>
<canvas id="lineChart" height="190"></canvas>

Categories

Resources