How can I use LinerGradient() by variable in Flutter? - gradient

const LinearGradient Gradient_Color = LinearGradient(colors: [
Top_gradient,
Bottom_gradient
]);

Related

Vue 3 & Chart JS not updating labels

I'm trying to make a simple Vue3 app which show graphs using Chart.js
For this I'm trying to replicate the code shown in the vue-chart-3 plugin doc, which shows an example using a Doughnut chart
My objective is to show a Line graph with a horizontal time axis
The code is a simple App.vue which template is
<template>
<LineChart v-bind="lineChartProps" />
</template>
And the script part:
<script lang="ts">
import { computed, defineComponent, ref } from "vue";
import { LineChart, useLineChart } from "vue-chart-3";
import { Chart, ChartData, ChartOptions, registerables } from "chart.js";
Chart.register(...registerables);
export default defineComponent({
name: "App",
components: { LineChart },
setup() {
const dataValues = ref([30, 40, 60, 70, 5]);
const dataLabels = ref(["Paris", "Nîmes", "Toulon", "Perpignan", "Autre"]);
const toggleLegend = ref(true);
const testData = computed<ChartData<"doughnut">>(() => ({
labels: dataLabels.value,
datasets: [
{
data: dataValues.value,
backgroundColor: [
"#77CEFF",
"#0079AF",
"#123E6B",
"#97B0C4",
"#A5C8ED",
],
},
],
}));
const options = computed<ChartOptions<"doughnut">>(() => ({
scales: {
myScale: {
type: "logarithmic",
position: toggleLegend.value ? "left" : "right",
},
},
plugins: {
legend: {
position: toggleLegend.value ? "top" : "bottom",
},
title: {
display: true,
text: "Chart.js Doughnut Chart",
},
},
}));
const { lineChartProps, lineChartRef } = useLineChart({
chartData: testData,
options,
});
function switchLegend() {
toggleLegend.value = !toggleLegend.value;
}
return {
switchLegend,
testData,
options,
lineChartRef,
lineChartProps,
};
},
mounted() {
if (localStorage.data == undefined) {
localStorage.data = JSON.stringify(this.data);
} else {
this.data = localStorage.data;
}
let dataProcessed = JSON.parse(this.data);
// console.log(JSON.parse(this.data));
console.log(dataProcessed.data);
var dates = [];
// Obtain dates from dataProcessed Array
for (var i = 0; i < dataProcessed.data.length; i++) {
dates.push(dataProcessed.data[i].date);
}
this.testData.labes = dates;
console.log(dates);
},
});
</script>
The objective is that the mounted hook gets certain parameters of the LocalStorage and put them in the "labels" array of the "testData" variable, which is the one which aparently stores the X axis data of the chart.
In the VUE developer tool, it can be seen how this assignation process is done correctly, but in the chart of the left side, the data have not been updated.
Thank you for your help :D

Apex Chart Customer tool tip doesn't work

I am trying to use the custom tooltip from Apex Charts, have tried multiple examples online but they dont seem to work.. I am getting a tool tip but it seems like its the standard tooltip.
const { _getSum } = require("../helper/dynamicFormat");
const express = require("express");
const router = express.Router();
const { Validator } = require("../middlewares");
const resolvers = require("../resolvers");
const db = require("../models");
const moment = require("moment");
const _ = require("lodash");
const { getRandomColors } = require("../helper/colors");
router.get(
"/",
[Validator.check("query").not().isEmpty()],
Validator,
async (req, res, next) => {
try {
const { query } = req.query;
const options = JSON.parse(query);
let idleData=[
{
x: '3R4785',
y: [
new Date(1789, 3, 1,18,30).getTime(),
new Date(1789, 3, 1,19,30).getTime(),
]},{
x: '3R4785',
y: [
new Date(1789, 3, 1,21).getTime(),
new Date(1789, 3, 1,22).getTime(),
]
}
]
let drivingData= [
{
x: '3R4785',
y: [
new Date(1789, 3, 1,22).getTime(),
new Date(1789, 3, 1,23).getTime()
]
},
]
let parkingData=[
{
x: '3R4785',
y: [
new Date(1789, 3, 1, 23).getTime(),
new Date(1789, 3, 1,24).getTime(),
]
},
]
res.render("millage", {
options: JSON.stringify({
series: [
{
name: 'Idle',
data:idleData
},
{
name: 'Driving',
data:drivingData
},
{
name: 'Parking',
data: parkingData
},
],
chart: {
height: 350,
type: 'rangeBar'
},
plotOptions: {
bar: {
horizontal: true,
barHeight: '50%',
rangeBarGroupRows: true
}
},
colors: [
"#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0",
"#3F51B5", "#546E7A", "#D4526E", "#8D5B4C", "#F86624",
"#D7263D", "#1B998B", "#2E294E", "#F46036", "#E2C044"
],
fill: {
type: 'solid'
},
xaxis: {
type: 'datetime',
format: 'hh mm'
},
tooltip: {
custom: function({series, seriesIndex, dataPointIndex, w}) {
var data = w.globals.initialSeries[seriesIndex].data[dataPointIndex];
console.log("tooltip",series,seriesIndex,dataPointIndex,w)
return '<ul>' +
'<li><b>Price</b>: ' + data.x + '</li>' +
'<li><b>Number</b>: ' + data.y + '</li>' +
'</ul>';
}
},
legend: {
position: 'right'
},
}),
});
} catch (error) {
console.log("🚀 ~ file: millage.js ~ line 13 ~ error", error);
}
}
);
module.exports = router;
I have tried multiple examples online, but nothing changes the standard tooltip.. I get a tooltip but it's not the one I want. Also when I try to console out the tooltip function, nothing comes..
I tried also made sure to use the latest apext charts
this is how I render the component:-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/apexcharts#latest"></script>
</head>
<body>
{{{body}}}
</body>
</html>
<div id="chart"></div>
<script>
const defaultOptions = {
}
const options = JSON.parse(`{{options}}`.replace(/"/g, '"'));
var chart = new ApexCharts(document.getElementById("chart"), { ...defaultOptions, ...options });
chart.render();
</script>

How to hide Chart.js data labels for small screens

I am trying to hide data labels generated by the data labels plugin for small screens.
I thought that I could use the onResize property of chartjs and set display to false when the width got small. This is much like the hide labels solution found here.
Unfortunately, I've not been able to get this to work. I have the following CodePen that doesn't work.
var moneyFormat = wNumb({
decimals: 0,
thousand: ',',
prefix: '$',
negativeBefore: '-'
});
var percentFormat = wNumb({
decimals: 0,
suffix: '%',
negativeBefore: '-'
});
/*
* Unregister chartjs-plugins-datalabels - not really necessary for this use case
*/
Chart.plugins.unregister(ChartDataLabels);
var doughnutdata = {
labels: ['Housing',
'Food',
'Transportation',
'Clothing',
'Healthcare',
'Childcare',
'Misc'],
datasets: [
{
backgroundColor: [
'#9B2A00',
'#5B5C90',
'#6B8294',
'#1A6300',
'#BE0000',
'#B8A853',
'#64A856'
],
borderColor: [
'#FFFFFF',
'#FFFFFF',
'#FFFFFF',
'#FFFFFF',
'#FFFFFF',
'#FFFFFF',
'#FFFFFF'
],
data: [88480, 57680, 40050, 18430, 23860, 25840, 17490]
}
]
};
var chartOptions = {
responsive: true,
maintainAspectRatio: true,
legend: {
labels: {
boxWidth: 20
}
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var index = tooltipItem.index;
return data.labels[index] + ': ' + moneyFormat.to(data.datasets[0].data[index]) + '';
}
}
},
plugins: {
datalabels: {
anchor: 'end',
backgroundColor: function (context) {
return context.dataset.backgroundColor;
},
borderColor: 'white',
borderRadius: 25,
borderWidth: 1,
color: 'white',
font: {
size: 10
},
formatter: function (value, pieID) {
var sum = 0;
var dataArr = pieID.chart.data.datasets[0].data;
dataArr.map(function (data) {
sum += data;
});
var percentage = percentFormat.to((value * 100 / sum));
return percentage;
}
}
}
};
var doughnutID = document.getElementById('doughnutchart').getContext('2d');
var pieChart = new Chart(doughnutID, {
plugins: [ChartDataLabels],
type: 'doughnut',
data: doughnutdata,
options: chartOptions,
onResize: function(chart, size) {
var showLabels = (size.width < 500) ? false : true;
chart.options = {
plugins: {
datalabels: {
display: showLabels
}
}
};
}
});
Any ideas concerning what I'm doing wrong (and fixes) would be greatly appreciated.
Responsiveness can be implemented using scriptable options and in your case, you would use a function for the display option that returns false if the chart is smaller than a specific size. (Example):
options: {
plugins: {
datalabels: {
display: function(context) {
return context.chart.width > 500;
}
}
}
}
As usual, as soon as I post a question I come up with an answer. One solution using inline plugin definitions is given at the following CodePen. If you put a browser into developer mode and shrink the window to less than 540 px, the data labels will vanish.
The code is shown below:
"use strict";
/* global Chart */
/* global wNumb */
/* global ChartDataLabels */
/*
* Unregister chartjs-plugins-datalabels - not really necessary for this use case
*/
Chart.plugins.unregister(ChartDataLabels);
var moneyFormat = wNumb({
decimals: 0,
thousand: ",",
prefix: "$",
negativeBefore: "-"
});
var percentFormat = wNumb({
decimals: 0,
suffix: "%",
negativeBefore: "-"
});
var doughnutdata = {
labels: [
"Housing",
"Food",
"Transportation",
"Clothing",
"Healthcare",
"Childcare",
"Misc"
],
datasets: [
{
backgroundColor: [
"#9B2A00",
"#5B5C90",
"#6B8294",
"#1A6300",
"#BE0000",
"#B8A853",
"#64A856"
],
borderColor: [
"#FFFFFF",
"#FFFFFF",
"#FFFFFF",
"#FFFFFF",
"#FFFFFF",
"#FFFFFF",
"#FFFFFF"
],
data: [88480, 57680, 40050, 18430, 23860, 25840, 17490]
}
]
};
var chartOptions = {
responsive: true,
maintainAspectRatio: true,
legend: {
labels: {
boxWidth: 20
}
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var index = tooltipItem.index;
return (
data.labels[index] +
": " +
moneyFormat.to(data.datasets[0].data[index]) +
""
);
}
}
},
plugins: {
datalabels: {
anchor: "end",
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderColor: "white",
borderRadius: 25,
borderWidth: 1,
color: "white",
font: {
size: 10
},
formatter: function(value, pieID) {
var sum = 0;
var dataArr = pieID.chart.data.datasets[0].data;
dataArr.map(function(data) {
sum += data;
});
var percentage = percentFormat.to(value * 100 / sum);
return percentage;
}
}
}
};
var doughnutID = document.getElementById("doughnutchart").getContext("2d");
var pieChart = new Chart(doughnutID, {
plugins: [
ChartDataLabels,
{
beforeLayout: function(chart) {
var showLabels = (chart.width) > 500 ? true : false;
chart.options.plugins.datalabels.display = showLabels;
}
},
{
onresize: function(chart) {
var showLabels = (chart.width) > 500 ? true : false;
chart.options.plugins.datalabels.display = showLabels;
}
}
],
type: "doughnut",
data: doughnutdata,
options: chartOptions
});
I hope that this is useful.

updating chart.js in ractive

For some data visualisation I use ractive and chart.js. The initial drawing works great, but I can't find a way to update the chart automatically when my data changes. So far I got (simplified):
const Stats = '<canvas id="myChart" width="400" height="400"></canvas>'
new Ractive ({
el: '#stats',
template: Stats,
magic: true,
modifyArrays: true,
data: {docs}, // <= some JSON Data
computed: {
Data1() {
let tempList = this.get('docs');
// rearrange & filter Data
return tempList ;
},
Data2() {
let tempList2 = this.get('docs');
// rearrange & filter Data
return tempList2 ;
},
Data3() {
let tempList3 = this.get('docs');
// rearrange & filter Data
return tempList3 ;
},
}
},
onrender: function () {
let DataSet1 = this.get('Data1');
let DataSet2 = this.get('Data2');
let DataSet3 = this.get('Data3');
let ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Data 1", "Data 1", "Data 3"],
datasets: [{
label: 'All my Data',
data: [DataSet1.length, DataSet2.length, DataSet3.length],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(75, 192, 192, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(255, 159, 64, 1)',
'rgba(75, 192, 192, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false
}
});
},
onchange: function () {
let newData = this.get('docs')
addData(myChart, label, newData)
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
}
});
Of Course I get an error in line chart.data.labels.push(label);, and also I'm quite sure that I would need my computed values in the onrenderfunction, not the initial Dataset. But I really have no clue how to get those into the update function, or if this function is the correct approach at all...
If you are working with 3rd party plugins I would recommend to use Ractive's decorators.
This post on ractivejs-and-jquery-plugins shows you a starting point how to implement a decorator based on a fileupload control.
In your case I would recommend to build a decorator with the data as parameter and do not forget to implement the UPDATE function (where in your case you gonna call the update method with the new data for your chart)
As I could not figure out how to write my own decorator for Chart.js I thought I post the solution that worked for me. I do not think it's best practice and for sure decorators would be a better way (therefore I do not mark this solution as correct answer), but it works:
const Stats = '<canvas id="myChart" width="400" height="400"></canvas>'
new Ractive ({
el: '#stats',
template: Stats,
magic: true,
modifyArrays: true,
data: {docs}, // <= some JSON Data
computed: {
Data1() {
let tempList = this.get('docs');
// rearrange & filter Data
return tempList ;
},
Data2() {
let tempList2 = this.get('docs');
// rearrange & filter Data
return tempList2 ;
},
Data3() {
let tempList3 = this.get('docs');
// rearrange & filter Data
return tempList3 ;
},
}
},
onrender: function () {
let DataSet1 = this.get('Data1');
let DataSet2 = this.get('Data2');
let DataSet3 = this.get('Data3');
let ctx = document.getElementById("myChart");
myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Data 1", "Data 1", "Data 3"],
datasets: [{
label: 'All my Data',
data: [DataSet1.length, DataSet2.length, DataSet3.length]
}]
}
});
},
onchange: function () {
let changedData1 = this.get('Data1');
let changedData2 = this.get('Data2');
let changedData3 = this.get('Data3');
myChart.data.datasets[0].data[0] = changedData1.length;
myChart.data.datasets[0].data[1] = changedData2.length;
myChart.data.datasets[0].data[2] = changedData3.length;
myChart.update();
}
}
});

Error when setting the center of a map as a dictionary value

I have an app developed with django: an user enters an integral in a form an gets redirected to a page that, depending of the input, it shows a map or another. The value that the user has entered is in the variable {{linea_numero}}
<div id="map"></div>
<script>
var LatLangParada = [
["{lat: 40.969092, lng: -5.675925}"],
["{lat: 38.737370, lng: -9.147660}"],
["{lat: 40.412944, lng: -3.681914}"],
["{lat: 41.385691, lng: 2.153859}"],
]
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: LatLangParada[{{linea_numero}}],
zoom: 8
});
}
</script>
I get the error
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in
property lat: not a number
I tried to delete the "" of the coordinates, but it doesn't work.
Thanks in advance
the sintax fo lat lng literal is {"lat": 40.969092, "lng": -5.675925}
so
and for center you should use only a lat lng literal not all the collection
<div id="map"></div>
<script>
var LatLangParada = [
[{"lat": 40.969092, "lng": -5.675925}],
[{"lat": 38.737370, "lng": -9.147660}],
[{"lat": 40.412944, "lng": -3.681914}],
[{"lat": 41.385691, "lng": 2.153859}],
]
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: LatLangParada[0],
zoom: 8
});
}
</script>