I'm trying to set theme using plugin in New version of chartjs 3.9.1, i'm trying to add "chartjs-plugin-colorschemes" plugin, link is: https://nagix.github.io/chartjs-plugin-colorschemes/.
In old version of chartjs v2.9.3 is working fine with this plugin.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="chartMenu">
<p>WWW.CHARTJS3.COM (Chart JS 3.9.1)</p>
</div>
<div class="chartCard">
<div class="chartBox" style="width: 500px">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-colorschemes/0.4.0/chartjs-plugin-colorschemes.min.js">
</script>
<script>
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [1, 2, 3].map(function (i) {
return {
label: 'Dataset ' + i,
data: [0, 0, 0, 0, 0, 0, 0].map(Math.random),
fill: false
}
})
};
const config = {
type: 'line',
data,
options: {
plugins: [
{
"colorschemes": {
scheme: 'brewer.RdYlBu3',
}
}]
},
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
</body>
</html>
Here is the code that I tried, can someone please guide me what i missed.
thanks.
It was never correctly updated for V3 so the only thing you can try is if the export they do also works for CDN version of distribution and try to register it. Otherwise you will need to wait until or if the plugin ever gets updated to work with V3 and above:
This might work if CDN version supports it, otherwise you are out of luck and need to stay with V2 or implement the plugin and coloring yourself:
Chart.register(ColorSchemesPlugin);
const data = {};
const config = {};
new Chart(ctx, config);
The demo site uses chart.js v2.8.0. As you can see on this page, the plugin you try to use doesn't work for chart.js v3 and later.
You probably can take a look at this pluging and adapt it to your need to generate the colors you want to use.
Here is some work around,
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getting Started with Chart JS with www.chartjs3.com</title>
</head>
<body>
<div class="chartMenu">
<p>WWW.CHARTJS3.COM (Chart JS 3.9.1)</p>
</div>
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"
integrity="sha512-UXumZrZNiOwnTcZSHLOfcTs0aos2MzBWHXOHOuB0J/R44QB0dwY5JgfbvljXcklVf65Gc4El6RjZ+lnwd2az2g=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/1.2.1/chartjs-plugin-zoom.min.js"
integrity="sha512-klQv6lz2YR+MecyFYMFRuU2eAl8IPRo6zHnsc9n142TJuJHS8CG0ix4Oq9na9ceeg1u5EkBfZsFcV3U7J51iew=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
const dt = [];
const labels = [];
for (let index = 1; index < 20; index++) {
labels.push("Label_" + index);
dt.push(index);
}
var ThemeDictionary = {
Classic10: ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"],
ClassicMedium10: ["#729ece", "#ff9e4a", "#67bf5c", "#ed665d", "#ad8bc9", "#a8786e", "#ed97ca", "#a2a2a2", "#cdcc5d", "#6dccda"],
ClassicLight10: ["#aec7e8", "#ffbb78", "#98df8a", "#ff9896", "#c5b0d5", "#c49c94", "#f7b6d2", "#c7c7c7", "#dbdb8d", "#9edae5"],
Classic20: ["#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f", "#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5"],
ClassicGray5: ["#60636a", "#a5acaf", "#414451", "#8f8782", "#cfcfcf"],
ClassicColorBlind10: ["#006ba4", "#ff800e", "#ababab", "#595959", "#5f9ed1", "#c85200", "#898989", "#a2c8ec", "#ffbc79", "#cfcfcf"],
ClassicTrafficLight9: ["#b10318", "#dba13a", "#309343", "#d82526", "#ffc156", "#69b764", "#f26c64", "#ffdd71", "#9fcd99"],
ClassicPurpleGray6: ["#7b66d2", "#dc5fbd", "#94917b", "#995688", "#d098ee", "#d7d5c5"],
ClassicPurpleGray12: ["#7b66d2", "#a699e8", "#dc5fbd", "#ffc0da", "#5f5a41", "#b4b19b", "#995688", "#d898ba", "#ab6ad5", "#d098ee", "#8b7c6e", "#dbd4c5"],
ClassicGreenOrange6: ["#32a251", "#ff7f0f", "#3cb7cc", "#ffd94a", "#39737c", "#b85a0d"],
ClassicGreenOrange12: ["#32a251", "#acd98d", "#ff7f0f", "#ffb977", "#3cb7cc", "#98d9e4", "#b85a0d", "#ffd94a", "#39737c", "#86b4a9", "#82853b", "#ccc94d"],
ClassicBlueRed6: ["#2c69b0", "#f02720", "#ac613c", "#6ba3d6", "#ea6b73", "#e9c39b"],
ClassicBlueRed12: ["#2c69b0", "#b5c8e2", "#f02720", "#ffb6b0", "#ac613c", "#e9c39b", "#6ba3d6", "#b5dffd", "#ac8763", "#ddc9b4", "#bd0a36", "#f4737a"],
ClassicCyclic13: ["#1f83b4", "#12a2a8", "#2ca030", "#78a641", "#bcbd22", "#ffbf50", "#ffaa0e", "#ff7f0e", "#d63a3a", "#c7519c", "#ba43b4", "#8a60b0", "#6f63bb"],
}
var Theme = "Classic10"
// setup
const data = {
labels: labels,
datasets: [{
label: 'Weekly Sales',
data: dt,
backgroundColor: ThemeDictionary[Theme],
borderWidth: 1
}]
};
// config
const config = {
type: 'bar',
data,
options: {
scales: {
y: {
beginAtZero: true
}
},
plugins: {
zoom: {
zoom: {
wheel: {
enabled: true
}
}
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
</body>
</html>
You can create you own theme colors and add into "ThemeDictionary" dictionary with key and set your key into "Theme" variable, that's it.
Please suggest if anything I missed.
Related
In Vue.js 2 I would like to convert a string into a function call so that it can be set as an event handler.
I believe this would be very practical, specially when dynamically creating lots of elements (e.g. buttons) based on a list of objects.
new Vue({
el: "#app",
data: {
myArray: [
{ value: 1, fn: "firstMethod" },
{ value: 2, fn: "secondMethod" },
],
},
methods: {
firstMethod() {
console.log("'firstMethod' was executed.");
},
secondMethod() {
console.log("'secondMethod' was executed.");
},
},
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<template v-for="elem in myArray">
<button #click="elem.fn"> <!-- Here is where I am stucked. -->
<!-- <button> -->
{{elem.value}}
</button>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="script.js"></script>
</body>
</html>
My first attempt at doing this was setting the fn properties in myArray as sort of pointers to the corresponding functions with this (e.g. fn: this.firstMethod). The problem is, I believe, that at the time of the definition, these functions are still unkown, as I get: [Vue warn]: Invalid handler for event "click": got undefined.
Is what I am trying to achieve even possible? Is there a downside with this strategy that I am overlooking?
Try to create one method, which will be working with all buttons
new Vue({
el: "#app",
data: {
myArray: [
{ value: 1, fn: "firstMethod" },
{ value: 2, fn: "secondMethod" },
],
},
methods: {
basicMethod(name) {
console.log(`'${name}' was executed.`);
if(name === 'firstMethod') {
//some logic, and so on for other methods if u need
}
},
},
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<template v-for="elem in myArray">
<button #click="basicMethod(elem.fn)"> <!-- Here is where I am stucked. -->
<!-- <button> -->
{{elem.value}}
</button>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="script.js"></script>
</body>
</html>
You can use a generic method provided with the function name the call this[ fn ]();.
But for security reasons, you might want these custom methods to be in an object, not just on the main this, so other methods can't be called.
Also, you want to check if the method exists before calling it.
It would look something like this:
new Vue({
el: "#app",
data: {
myArray: [
{ value: 1, fn: "firstMethod" },
{ value: 2, fn: "secondMethod" },
{ value: 3, fn: "nonExistingMethod" }, // Won't throw an error
{ value: 4, fn: "someImportantSecureMethod" }, // Won't be called
],
customMethods: {
firstMethod: function() {
console.log("'firstMethod' was executed.");
},
secondMethod: function() {
console.log("'secondMethod' was executed.");
},
},
},
methods: {
callCustomMethod(fn) {
// Make sure it exists
if (typeof this.customMethods[fn] === "function") {
// Only methods inside the customMethods object are available
this.customMethods[fn]();
}
},
someImportantSecureMethod() {
console.log('The method may not be exposed to dynamic calling!');
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template v-for="elem in myArray">
<button #click="callCustomMethod(elem.fn)">
<!-- <button> -->
{{elem.value}}
</button>
</template>
</div>
As a side note:
You might also considering using custom events (see docs) for this. Using $emit('custom-event-name') as the v-on:click handler and have your custom methods as event listeners. (Makes it easy when you later might want to make the items into separate components.)
I am new in javascript and have to use the libraries of Chart.js
I have in a jsp file the following instruction for a button
window.open("test.jsp", "width="+800+ "height="+580);
and in the test.jsp file this code:
<!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>test</title>
<script type=“text/javascript”>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/Chart.min.js"></script>
<script type=“test.jsp”>
<script type=“text/javascript”>
var ctx = document.getElementById('myChart');
var stars = [135850, 52122, 148825, 16939, 9763];
var frameworks = ['React', 'Angular', 'Vue', 'Hyperapp', 'Omi'];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: frameworks,
datasets: [{
label: 'Github Stars',
data: stars
}]
},
})
</head>
<body>
<canvas id="myChart" width="800" height="400"></canvas>
</body>
</html>
I am able to open the new window but I can't see anything inside.
I would like to all the code runs in jsp file, without delegating to js and html files outside.
There are different problems in your code.
The referenced Chart.js library does not exist. Instead of ...Chart.min.js, write ...chart.min.js (lowercase).
Define your custom JS code in a function and execute it only once the body and its canvas are fully loaded (<body onload="drawChart()">).
Please take a look at below runnable HTML code, it should run similarly with JSP.
<!DOCTYPE html>
<html lang="en">
<head>
<title>test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script type="text/javascript">
function drawChart() {
var stars = [135850, 52122, 148825, 16939, 9763];
var frameworks = ['React', 'Angular', 'Vue', 'Hyperapp', 'Omi'];
new Chart('myChart', {
type: 'bar',
data: {
labels: frameworks,
datasets: [{
label: 'Github Stars',
data: stars
}]
},
});
}
</script>
</head>
<body onload="drawChart()">
<canvas id="myChart" width="800" height="400"></canvas>
</body>
</html>
I aim to plot a line graph on the webpage using flask and charts.js I am just a beginner so I followed the link(https://www.youtube.com/watch?v=E2hytuQvLlE&lc=UgzWBrS2GEx1BnNgs2V4AaABAg) to implement this program but it not working the error on the webpage is mentioned at the end of the question.
This is my python code
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/home")
def home():
plot_data = [
("3-01-2020", 6),
("3-02-2020", 13),
("3-03-2020", 14),
("3-04-2020", 41),
("1-05-2020", 10),
("3-06-2020", 0),
("3-07-2020", 16),
("3-08-2020", 10),
("3-09-2020", 17),
("3-10-2020", 19),
]
labels = []
values = []
for row in plot_data:
labels.append(row[1])
values.append(row[0])
return render_template('graph.html', lables=labels, values=values)
if __name__ == "__main__":
app.run(debug=True)
This is my HTML code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart view</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.min.js"></script>
</head>
<body>
<canvas id = "voltage_graph" width="900" height="400"></canvas>
<script>
var ctx = document.getElementById("voltage_graph").getContext("2d");
var lineChart = new Chart(ctx,{
type: "line",
data:{
labels: {{labels | safe}}
datasets: [
{
label: "BMS_CELL_01_voltage",
data: {{values | safe}},
fill : false,
borderColor:"rgb(75,192,192)",
lineTension: 0.1
}
]
},
Options:{
responsive: false
}
});
</script>
</body>
</html>
This is my terminal output
C:\Users\rohit\AppData\Local\Programs\Python\Python37\python.exe C:/Users/rohit/PycharmProjects/flask-projects/applicaton.py
* Serving Flask app 'application (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 275-482-683
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
when I run this all I get is an error on the website stating as above
any help would be appreciated, thanks in advance.
A few issues in the code you posted:
lables= is mispelled in app.py, should be labels=
labels.append(row[1]) should use row[0], assuming you want the dates to be used as labels (and vice versa, where values should use row[1] instead)
labels: {{labels | safe}} is missing a comma at the end
Once you fix these issues, your graph will show up when you navigate to localhost:5000/home.
EDIT: For completeness, here is the working code. In app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/home")
def home():
plot_data = [
("3-01-2020", 6),
("3-02-2020", 13),
("3-03-2020", 14),
("3-04-2020", 41),
("1-05-2020", 10),
("3-06-2020", 0),
("3-07-2020", 16),
("3-08-2020", 10),
("3-09-2020", 17),
("3-10-2020", 19),
]
labels = []
values = []
for row in plot_data:
labels.append(row[0])
values.append(row[1])
print(labels)
print(values)
return render_template('graph.html', labels=labels, values=values)
if __name__ == "__main__":
app.run(debug=True)
And in templates/graph.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart view</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.min.js"></script>
</head>
<body>
<canvas id = "voltage_graph" width="900" height="400"></canvas>
<script>
var ctx = document.getElementById("voltage_graph").getContext("2d");
var lineChart = new Chart(ctx,{
type: "line",
data:{
labels: {{labels | safe}},
datasets: [
{
label: "BMS_CELL_01_voltage",
data: {{values | safe}},
fill : false,
borderColor:"rgb(75,192,192)",
lineTension: 0.1
}
]
},
Options:{
responsive: false
}
});
</script>
</body>
</html>
I'm creating web application with zTree.
The tree is built based on data from the Golang backend.
Tree leaves change custom icons while the application is running.
How to change icons, based on backend data, without refreshing the page?
With http-equiv="refresh" page is blinking and lost focus. Here is working but blinking sample with zTree and refresh (I cut of backend part for simplicity):
<HTML>
<HEAD>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" content="5">
<link rel="stylesheet" href="../static/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="../static/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="../static/js/jquery.ztree.core.js"></script>
</HEAD>
<BODY>
<div id="app">
<TABLE>
<TR>
<TD width=260px valign=top>
<ul id="tree" class="ztree"></ul>
</TD>
<TD valign=top>
<p>Some text</p>
</TD>
</TR>
</TABLE>
<SCRIPT type="text/javascript">
var zTree;
var setting = {
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: ""
}
}
};
var zNodes = [
{id: 1, pId: 0, name: "root", icon:"../static/css/zTreeStyle/img/diy/c16green.png"},
{id: 2, pId: 1, name: "leaf", icon:"../static/css/zTreeStyle/img/diy/c16red.png"},
];
$(document).ready(function () {
var t = $("#tree");
t = $.fn.zTree.init(t, setting, zNodes);
});
</script>
</div>
</BODY>
</HTML>
I try to use Vue.js, but cannot bind data to zTree. Here is not working sample with Vue.js data binding inside script tag:
<HTML>
<HEAD>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../static/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="../static/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="../static/js/jquery.ztree.core.js"></script>
<script src="https://unpkg.com/vue"></script>
</HEAD>
<BODY>
<div id="app">
<TABLE>
<TR>
<TD width=260px valign=top>
<ul id="tree" class="ztree"></ul>
</TD>
<TD valign=top>
<p>{{ now }}</p>
<p>Some text</p>
</TD>
</TR>
</TABLE>
<SCRIPT type="text/javascript">
var zTree;
var setting = {
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: ""
}
}
};
var zNodes = [
{id: 1, pId: 0, name: "root", icon:"../static/css/zTreeStyle/img/diy/c16green.png"},
{id: 2, pId: 1, name: "leaf", icon:"../static/css/zTreeStyle/img/diy/c16red.png"},
{id: 3, pId: 1, name: "foo", icon: {{ customIcon }} },
];
$(document).ready(function () {
var t = $("#tree");
t = $.fn.zTree.init(t, setting, zNodes);
});
const app = new Vue({
el: '#app',
data: {
now: new Date(),
customIcon : "../static/css/zTreeStyle/img/diy/c16green.png"
},
methods: {
updateDate() {
this.now = new Date();
}
},
mounted() {
setInterval(() => {
this.updateDate();
}, 1000);
},
})
</script>
</div>
</BODY>
</HTML>
Zipped sample (examples are inside template directory): https://drive.google.com/file/d/1Ihv8jLdsEz93aUrFjEugD1l6YvslaUT8
The solution contains a few steps:
use "go-echo-vue" for communication between backend and frontend like here: https://github.com/covrom/go-echo-vue
update zTree data using vue-resource and timer like this:
<script>
new Vue({
// ....
methods: {
updateZNodes() {
// запрашиваем дерево :)
this.$http.get('/znodes').then(function (response) {
zNodes = response.data.items ? response.data.items : []
}, function (error) {
console.log(error)
});
},
},
mounted() {
setInterval(() => {
this.updateZNodes();
}, 5000);
},
// ....
})</script>
refrest zTree nodes information using js:
<script language="JavaScript">
function refreshNode() {
var treeObj = $.fn.zTree.getZTreeObj("tree");
var nodes = treeObj.getNodes();
if (nodes.length > 0) {
for (let i = 0; i < nodes.length; i++) {
c = "static/css/zTreeStyle/img/diy/c16grey.png";
if (zNodes.length >= i) {
c = zNodes[i].icon
}
nodes[i].icon = c;
treeObj.updateNode(nodes[i]);
}
}
};
const timerId = setInterval(
() => {
refreshNode();
},
5000
);
</script>
add async zTree settings:
<script language="JavaScript">
var setting = {
// ....
async: {
enable: true,
url: "",
autoparam: ["id", "icon"],
datatype: "json",
},
// ....
};
</script>
That's all. So we have Vue function http.get to get fresh data from backend, global js variable to use that data both inside Vue code segment and JavaScript blocks.
PS additional information: https://www.tutorialfor.com/blog-188266.htm
I would like to create an interactive image using goJs, however when i try and follow the tutorial to create a basic visual the output I get is just a blank box and not an interactive image with the words 'Alpha' and 'Beta' connected by a line.
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/gojs/release/go-debug.js"></script>
<script src="go.js"></script>
<script>
function init() {
var $ = gp.GraphObject.make;
myDiagram = $(go.Diagram, "decisionTree");
var nodeDataArray = [
{ key: "Alpha" },
{ key: "Beta" }
];
var linkDataArray = [
{ to: "Beta", from: "Alpha" }
];
myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray)
}
</script>
</head>
<body onload="init"()>
<div id="decisionTree" style="width:300px; height:300px; border:1px solid black;"></div>
</body>
</html>
Tutorial: https://www.youtube.com/watch?v=7cfHF7yAoJE#action=share
You are loading two different versions of the GoJS library. I suggest you remove the line:
<script src="go.js"></script>
EDIT: In addition, there are some typos that I missed before when just reading your code. This actually works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/gojs/release/go-debug.js"></script>
<script>
function init() {
var $ = go.GraphObject.make;
var myDiagram = $(go.Diagram, "decisionTree");
var nodeDataArray = [
{ key: "Alpha" },
{ key: "Beta" }
];
var linkDataArray = [
{ to: "Beta", from: "Alpha" }
];
myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray)
}
</script>
</head>
<body onload="init()">
<div id="decisionTree" style="width:300px; height:300px; border:1px solid black;"></div>
</body>
</html>