How to bring this function out of methods inside this Vue component? - javascript

I have this Vue component BarChart.vue which is from
https://github.com/apexcharts/vue3-apexcharts
The script portion of this component is as follows;
<script>
/* eslint-disable */
export default {
name: "BarExample",
data: function() {
return {
chartOptions: {
plotOptions: {
bar: {
horizontal: true
}
},
xaxis: {
categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
}
},
series: [
{
name: "series-1",
data: [30, 40, 45, 50, 49, 60, 70, 91]
}
]
};
},
methods: {
updateChart() {
const max = 90;
const min = 20;
const newData = this.series[0].data.map(() => {
return Math.floor(Math.random() * (max - min + 1)) + min;
});
const colors = ["#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0"];
// Make sure to update the whole options config and not just a single property to allow the Vue watch catch the change.
this.chartOptions = {
colors: [colors[Math.floor(Math.random() * colors.length)]]
};
// In the same way, update the series option
this.series = [
{
data: newData
}
];
}
}
};
</script>
I want to bring updateChart() out of methods such that it is a separate function by itself.
This is what I did;
<script>
/* eslint-disable */
export default {
name: "BarExample",
data: function() {
return {
chartOptions: {
plotOptions: {
bar: {
horizontal: true
}
},
xaxis: {
categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
}
},
series: [
{
name: "series-1",
data: [30, 40, 45, 50, 49, 60, 70, 91]
}
]
};
},
methods: {
updateChart(),
}
};
updateChart() {
const max = 90;
const min = 20;
const newData = this.series[0].data.map(() => {
return Math.floor(Math.random() * (max - min + 1)) + min;
});
const colors = ["#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0"];
// Make sure to update the whole options config and not just a single property to allow the Vue watch catch the change.
this.chartOptions = {
colors: [colors[Math.floor(Math.random() * colors.length)]]
};
// In the same way, update the series option
this.series = [
{
data: newData
}
];
}
}
</script>
I received an error Parsing error: Unexpected token ,
I am using vue3 and apexcharts.

Remove the () like since that means that you're running the method:
methods: {
updateChart,
}
or
methods: {
updateChart : updateChart,
}

I would like to answer my own question for the sake of completion as there were other syntax errors to be fixed.
I credit my answer to #Thomas in the comments section.
<script>
/* eslint-disable */
export default {
name: "BarExample",
data: function() {
return {
chartOptions: {
plotOptions: {
bar: {
horizontal: true
}
},
xaxis: {
categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
}
},
series: [
{
name: "series-1",
data: [30, 40, 45, 50, 49, 60, 70, 91]
}
]
};
},
methods: {
updateChart,
}
};
function updateChart() {
const max = 90;
const min = 20;
const newData = this.series[0].data.map(() => {
return Math.floor(Math.random() * (max - min + 1)) + min;
});
const colors = ["#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0"];
// Make sure to update the whole options config and not just a single property to allow the Vue watch catch the change.
this.chartOptions = {
colors: [colors[Math.floor(Math.random() * colors.length)]]
};
// In the same way, update the series option
this.series = [
{
data: newData
}
];
}
</script>

Related

uplot freezing, when zooming, using svelte, nodered and uibuilder

uplot is used to dislay timeseries data from VictoriaMetrics database.
For the backend Node-Red is used to forward and recieve the query with node-red-contrib-uibuilder.
It works basically and is very fast.
The problem is, when I try to zoom into the uplot graph, my browser (Chrome, Firefox, Edge) freezes. It seems to run out of memory.
Here are parts of my code, using svelte.
<script>
import { onMount } from "svelte";
import { query } from "../lib/uibStore";
import { transformToUplot } from "../lib/helper";
// import uPlot from "uplot";
import Browsebar from "../components/Browsebar.svelte";
import TimerangeSelect from "../components/TimerangeSelect.svelte";
let uplotdiv; //
let opts = {
title: "Temperaturen1",
id: "chart1",
class: "my-chart",
width: 1000,
height: 600,
series: [
{},
{
show: true, // initial toggled state (optional)
spanGaps: true,
label: "RT",
stroke: "red", // series style
scale: "Temperature",
value: (self, rawValue) => rawValue.toFixed(1) + "°C",
},
{
show: true,
spanGaps: true,
label: "KT",
stroke: "green",
scale: "Temperature",
value: (self, rawValue) => rawValue.toFixed(1) + "°C",
},
{
show: true,
spanGaps: true,
label: "VT",
stroke: "blue",
scale: "Temperature",
value: (self, rawValue) => rawValue.toFixed(1) + "°C",
},
],
scales: {
x: { time: true },
Temperature: {
auto: true,
// range: [-10, 20],
side: 3,
},
},
axes: [
{},
{
scale: "Temperature",
values: (self, ticks) => ticks.map((rawValue) => rawValue.toFixed(1) + "°C"),
},
],
cursor: { drag: { x: true, y: true } },
};
let plot; // = new uPlot(opts);
let uPlot;
let d = [[0], [0], [0], [0]];
let resolved = false;
$: uisend($query); //use uibilder.send, if query changes which occurs when timerange or nav index changes
//send a victoriametrics query to the backend, _q is part of query
function uisend(_q) {
// Example 'uvr_prozess_celsius{ort="1"}&start=-3d&step=60s'
uibuilder.send({ topic: "getVMetrics", payload: _q });
}
onMount(async () => {
uisend($query);
const uplotModule = await import("https://unpkg.com/uplot#1.6.22/dist/uPlot.esm.js");
uPlot = uplotModule.default;
plot = new uPlot(opts, [[0], [0], [0], [0]], uplotdiv);
});
uibuilder.onChange("msg", function (msg) {
// load Metrics via Node-Red's uibuilder, serverside
if (msg.topic === "getVMetrics") {
resolved = true;
if (msg.payload.data.result.length > 0) {
d = transformToUplot(msg.payload.data);
plot.setData(d);
}
}
});
</script>
<svelte:head>
<link rel="stylesheet" href="https://unpkg.com/uplot#1.6.22/dist/uPlot.min.css" />
</svelte:head>
<Browsebar>
<TimerangeSelect />
</Browsebar>
<hr />
<div bind:this={uplotdiv} />
{#if resolved}
<code>{$query}</code>
{:else}
<h4>lade Metriken... {$query}</h4>
{/if}
<hr />
Has anyone experienced freezing with uplot? What did you do?
Lucky me, I found the problem. It had to do with the way I transformed the victoriametrics data. On every timestamp I did Number(timestamp).toFixed(0). Without toFixed(0) it is working now. :)
//transform raw data from metrics query to the uplot format
export function transformToUplot(dt) {
let udata = []; //2d data array, conforming uPlot
let tsd = []; //timestamp array
//from first result take only the timestamps
for (let t of dt.result[0].values) {
// tsd.push(Number(t[0]).toFixed(0)); //this was bad!!!!, it lead to freezing
tsd.push(Number(t[0]));
}
udata.push(tsd);
//then the values
for (let r of dt.result) {
let sd = [];
for (let d of r.values) {
let val = Number(d[1]);
sd.push(val);
}
udata.push(sd);
}
return udata;
}
Thanks for your interest!

hellp for combin tvjs-xp and trading-vue-js

hi i want charting stock data in web page.
i found sample project in github
https://github.com/tvjsx/tvjs-xp
i change code and connect the binance and receive and charting real time data.
i have some problem after add online receive data chart lagend bouttun not work and i cant add layer.
please help me.
thanks
<trading-vue :data="dc" :width="this.width" :height="this.height"
title-txt="TVJS XP" :key="resetkey"
:chart-config="{DEFAULT_LEN:70}"
ref="tvjs"
:legend-buttons="['display', 'settings', 'up', 'down', 'add', 'remove']"
:toolbar="true"
:index-based="index_based"
:color-back="colors.colorBack"
:color-grid="colors.colorGrid"
:color-text="colors.colorText"
:extensions="ext"
:overlays="ovs"
:x-settings="xsett">
</trading-vue>
<span class="gc-mode">
<input type="checkbox" v-model="index_based">
<label>Index Based</label>
</span>
export default {
name: 'DataHelper',
icon: '⚡',
description: 'Real-time updates. Play with DataCube in the console',
props: ['night', 'ext', 'resetkey'],
components: {
TradingVue
},
mounted() {
window.addEventListener('resize', this.onResize)
this.onResize()
// Load the last data chunk & init DataCube:
let now = Utils.now()
this.load_chunk([now - Const.HOUR4, now]).then(data => {
this.dc = new DataCube({
ohlcv: data['dc.data'],
// onchart: [{
// type: 'EMAx6',
// name: 'Multiple EMA',
// data: []
// }],
offchart: [
// {
// type: 'BuySellBalance',
// name: 'Buy/Sell Balance, $lookback',
// data: [],
// settings: {}
// },
{
name: "RSI, 20",
type: "Range",
data: [],
settings: {
"upper": 70,
"lower": 30,
"backColor": "#9b9ba316",
"bandColor": "#666"
}
},
],
datasets: [{
type: 'Trades',
id: 'binance-btcusdt',
data: []
}]
}, { aggregation: 100 })
// Register onrange callback & And a stream of trades
this.dc.onrange(this.load_chunk)
this.$refs.tvjs.resetChart()
this.stream = new Stream(WSS)
this.stream.ontrades = this.on_trades
window.dc = this.dc // Debug
window.tv = this.$refs.tvjs // Debug
})
},
methods: {
onResize(event) {
this.width = window.innerWidth
this.height = window.innerHeight - 50
},
// New data handler. Should return Promise, or
// use callback: load_chunk(range, tf, callback)
async load_chunk(range) {
let [t1, t2] = range
let x = 'BTCUSDT'
let q = `${x}&interval=1m&startTime=${t1}&endTime=${t2}`
let r = await fetch(URL + q).then(r => r.json())
return this.format(this.parse_binance(r))
},
// Parse a specific exchange format
parse_binance(data) {
if (!Array.isArray(data)) return []
return data.map(x => {
for (var i = 0; i < x.length; i++) {
x[i] = parseFloat(x[i])
}
return x.slice(0,6)
})
},
format(data) {
// Each query sets data to a corresponding overlay
return {
'dc.data': data
// other onchart/offchart overlays can be added here,
// but we are using Script Engine to calculate some:
// see EMAx6 & BuySellBalance
}
},
on_trades(trade) {
this.dc.update({
t: trade.T, // Exchange time (optional)
price: parseFloat(trade.p), // Trade price
volume: parseFloat(trade.q), // Trade amount
'datasets.binance-btcusdt': [ // Update dataset
trade.T,
trade.m ? 0 : 1, // Sell or Buy
parseFloat(trade.q),
parseFloat(trade.p)
],
// ... other onchart/offchart updates
})
}
},
beforeDestroy() {
window.removeEventListener('resize', this.onResize)
if (this.stream) this.stream.off()
},
computed: {
colors() {
return this.$props.night ? {} : {
colorBack: '#fff',
colorGrid: '#eee',
colorText: '#333'
}
},
},
data() {
return {
dc: {},
width: window.innerWidth,
height: window.innerHeight,
index_based: false,
xsett: {
'grid-resize': { min_height: 30 }
},
ovs: Object.values(Overlays),
}
}
}

ZingChart Not Rendering In GrapesJs Custom Component Type

I'm attempting to integrate ZingChart as a custom component type in GrapesJs. I've followed some examples and have implemented the following plugin.
blocks.js
import { lineChartRef, chartType } from './consts';
export default (editor, opt = {}) => {
const c = opt;
const bm = editor.BlockManager;
if (c.blocks.indexOf(lineChartRef) >= 0) {
bm.add(lineChartRef, {
label: c.labelLineChart,
content: `
<div data-gjs-type="${chartType}" id="myChart"></div>
`
});
}
};
components.js
import { chartType } from './consts';
export default (editor, opt = {}) => {
const domc = editor.DomComponents;
const defaultType = domc.getType('default');
const defaultModel = defaultType.model;
domc.addType(chartType, {
model: defaultModel.extend(
{
defaults: {
...defaultModel.prototype.defaults,
script: function() {
if (typeof zingchart == 'undefined') {
var script = document.createElement('script');
script.src =
'https://cdn.zingchart.com/zingchart.min.js';
document.body.appendChild(script);
}
}
}
},
{
isComponent: el => {
if (
el.getAttribute &&
el.getAttribute('data-gjs-type') === chartType
) {
return {
type: chartType
};
}
}
}
),
view: {
onRender() {
renderZingChart.bind(this)();
}
}
});
function renderZingChart() {
const data = {
type: 'bar',
title: {
text: 'Data Basics',
fontSize: 24
},
legend: {
draggable: true
},
scaleX: {
// Set scale label
label: { text: 'Days' },
// Convert text on scale indices
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
scaleY: {
label: { text: 'Temperature (°F)' }
},
plot: {
animation: {
effect: 'ANIMATION_EXPAND_BOTTOM',
method: 'ANIMATION_STRONG_EASE_OUT',
sequence: 'ANIMATION_BY_NODE',
speed: 275
}
},
series: [
{
// plot 1 values, linear data
values: [23, 20, 27, 29, 25, 17, 15],
text: 'Week 1'
},
{
// plot 2 values, linear data
values: [35, 42, 33, 49, 35, 47, 35],
text: 'Week 2'
},
{
// plot 2 values, linear data
values: [15, 22, 13, 33, 44, 27, 31],
text: 'Week 3'
}
]
};
const chart = {
id: 'myChart',
data
};
zingchart.render(chart);
}
};
index.js
import grapesjs from 'grapesjs';
import loadBlocks from './blocks';
import loadComponents from './components';
import { lineChartRef } from './consts';
export default grapesjs.plugins.add('fndy-charts', (editor, opts = {}) => {
let c = opts;
let defaults = {
blocks: [lineChartRef],
defaultStyle: 1,
labelLineChart: 'Line Chart'
};
// Load defaults
for (let name in defaults) {
if (!(name in c)) c[name] = defaults[name];
}
loadBlocks(editor, c);
loadComponents(editor, c);
});
consts.js
export const lineChartRef = 'line-chart';
export const chartType = 'chart';
When I add the block to the canvas, it renders, but the ZingChart inside does not. Some things I've tried already:
Verify that the ZingChart render function is being called.
Try moving the renderZingChart function call to different component hooks. Specifically, component:mount, view.init(), and view.onRender().
Move the renderZingChart function call to the script function as a script.onload callback. A similar example can be found here: https://grapesjs.com/docs/modules/Components-js.html#basic-scripts. This does render the ZingChart correctly but doesn't feel correct, and does not allow me to pass in parameters since the script function runs outside the scope of GrapesJs.
I'm running out of ideas so any guidance would be great! Thanks!
I'm making a chart component library with echarts, and the approach for rendering the chart would be similar. The only missing thing I see is element's id. It is an attribute that zing uses to render the chart.
I've made a small example which is obviously not production ready because the id of the block is static. This solves specifically the render problem to make the id dynamic you can do it listening to component:add event and add model id as attribute.
const plugin = editor => {
const {
BlockManager: bm
} = editor;
bm.add("mychart", {
label: "Chart",
content: {
tagName: "div",
attributes: {
id: 'myChart'
},
style: {
width: "300px",
height: "300px"
},
script: function() {
const init = () => {
const data = {
type: "bar",
title: {
text: "Data Basics",
fontSize: 24
},
legend: {
draggable: true
},
scaleX: {
// Set scale label
label: {
text: "Days"
},
// Convert text on scale indices
labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
},
scaleY: {
label: {
text: "Temperature (°F)"
}
},
plot: {
animation: {
effect: "ANIMATION_EXPAND_BOTTOM",
method: "ANIMATION_STRONG_EASE_OUT",
sequence: "ANIMATION_BY_NODE",
speed: 275
}
},
series: [{
// plot 1 values, linear data
values: [23, 20, 27, 29, 25, 17, 15],
text: "Week 1"
},
{
// plot 2 values, linear data
values: [35, 42, 33, 49, 35, 47, 35],
text: "Week 2"
},
{
// plot 2 values, linear data
values: [15, 22, 13, 33, 44, 27, 31],
text: "Week 3"
}
]
};
const chart = {
id: this.id,
data
};
zingchart.render(chart);
};
if (typeof zingchart == "undefined") {
var script = document.createElement("script");
script.onload = init;
script.src = "https://cdn.zingchart.com/zingchart.min.js";
document.body.appendChild(script);
} else {
init();
}
}
}
});
};
const editor = grapesjs.init({
container: "#gjs",
fromElement: true,
height: "100vh",
width: "auto",
storageManager: false,
panels: {
defaults: []
},
plugins: ["gjs-preset-webpage", plugin]
});
You can give a check here the chart is rendering.
Codepen
Hope that's enough, cheers!
I don't think you need to write very complicated code for using Zing charts.I will add a small sample code for making a chart block element , So when you drag and drop the block element then it will make the chart a part of the gjs div of grapesjs .I am using Highcharts.
editor.BlockManager.add('Blockhighcharts', {
label: 'Highchart',
category: 'CHART',
attributes: { class:'gjs-fonts gjs-f-b1' },
content: {
script: function () {
var container = "container"+Math.floor(Math.random() * 100);
$(this).attr("id",container);
$('#gridly_div').append($(this));
var myChart = Highcharts.chart(container, {
chart: {
type: 'bar',
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
The HTML code where the chart will be displayed is as follows.
<div id="gjs" style="height:0px; overflow:hidden;">
<style>
#gjs{
height: 100%;
width: 100%;
margin: 0;
}
</style>
<div id='gridly_div' class="gridly">
</div>

Am I using chart.update() correctly when trying to update the chart?

I have a chart created using chartjs and vuechartjs in my Vue project. Data will be passed in via mapGetters from my database. Data will change and the yAxes needs to be updated so that the ticks min and max and stepSize need to change corresponding to the available data being displayed. I wouldn't want my max to be 2500 with a step size of 250 when only displaying max data of 555. I want it to be closer to max 600 with stepSize of 50.
I read the documentation and it says to use chart.update(). I am trying to test this and it says that update cannot be read.
Error in v-on handler: "TypeError: Cannot read property 'update' of undefined"
Here is my code.
export default {
components: {
BarChart,
RoiCalculator
},
data() {
return {
data: [0,0,0,0,0,0,0,0,0,0,0],
maxFeedback: 0,
datacollection: null,
// Configure chart options here
options: {
tooltips: {
//Allows positioning of the tooltip to the event(mouse) position. Custom is the name of the position
//because that is the function created for Chart.Tooltip.positoners
position : 'custom',
callbacks: {
label: function(tooltipItem, data) {
var label = Math.floor(tooltipItem.yLabel*100)/100+" "+data.datasets[tooltipItem.datasetIndex].label;
return label;
}
}
},
maintainAspectRatio: false,
legend: {
//Hides the legend that would normally say NPS scores
display: false
},
// X and Y axes modified here
scales: {
// Allows you to customize the X axis
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Rating',
},
gridLines: {
display: false,
tickMarkLength: 0,
},
ticks: {
padding: 15,
showLabelBackdrop: false
}
}],
// Allows you to customize the Y axis
yAxes: [{
gridLines: {
tickMarkLength: 0,
},
ticks: {
padding: 15,
max: 500,
min: 0,
stepSize: 50
},
}]
},
},
}
},
mounted() {
this.populateFeedback();
},
computed: {
...mapGetters({
filteredFeedback: "initialFeedback"
}),
tid: function() {
return Spark.state.currentTeam.id;
} ,
},
watch: {
filteredFeedback: {
handler(){
this.loadData()
this.getMaxData()
this.resizeChart()
},
},
},
methods: {
...mapActions({
changeInitialFeedback: "changeInitialFeedback",
}),
updateChart(chart){
this.datacollection.datasets[0].data = [100, 200, 400, 600, 700, 1000, 120, 300, 305, 400, 555];
this.chartData.update();
},
loadData(){
this.datacollection = {
labels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
datasets: [{
label: '',
data: this.sortData(),
backgroundColor: [
'rgb(242, 74, 99)',
'rgb(242, 74, 99)',
'rgb(242, 74, 99)',
'rgb(242, 74, 99)',
'rgb(242, 74, 99)',
'rgb(242, 74, 99)',
'rgb(242, 74, 99)',
'rgb(253, 205, 61)',
'rgb(253, 205, 61)',
'rgb(9, 198, 117)',
'rgb(9, 198, 117)',
],
}]
}
},
resizeChart(){
console.log(this.Chart)
console.log(this.options.scales.yAxes[0].ticks.stepSize,'options')
if(!this.maxFeedback <= 0 && !this.maxFeedback >=100){
this.options.scales.yAxes[0].ticks.max = 100
this.options.scales.yAxes[0].ticks.stepSize = 10
}
else if (this.maxFeedback <= 500){
this.options.scales.yAxes[0].ticks.max = 500
this.options.scales.yAxes[0].ticks.stepSize = 50
}
else (this.maxFeedback <= 2200)
this.options.scales.yAxes[0].ticks.max = 2500
this.options.scales.yAxes[0].ticks.stepSize = 250
},
getMaxData(){
const maxFB = Math.max.apply(Math, this.datacollection.datasets[0].data)
console.log(maxFB, 'hello')
this.maxFeedback = maxFB
},
sortData(){
//Filters through all our filtered feedback data and adds them to each rating
const output=[0,0,0,0,0,0,0,0,0,0,0]
this.filteredFeedback.forEach(function (e) {
output[e.nps_rating] += 1
}
);
return output
},
populateFeedback() {
axios
.get(`/api/metricsPage/all/` + this.tid)
.then(response => {
// Filtering out incomplete data
let filteredFeedback = response.data.feedbacks.filter(feedback => {
return feedback.nps_icon || feedback.has_comments;
});
filteredFeedback = filteredFeedback.map(feedback =>{
feedback.service_rating = Number(feedback.service_rating);
feedback.product_rating = Number(feedback.product_rating);
feedback.delivery_rating = Number(feedback.delivery_rating);
feedback.nps_rating = Number(feedback.nps_rating);
return feedback;
})
// vuex calls to set global state
this.changeInitialFeedback({ initialFeedback: filteredFeedback });
})
.catch(error => {
throw error;
});
},
}
}
</script>
<script>
// This file is what exports the chart used in the index
// Imports and determines type of chart (Line, Bar, etc.)
import { Bar } from 'vue-chartjs'
//Creates custom positioning for the positoning of the tooltip.
Chart.Tooltip.positioners.custom = function(elements, eventPosition) { //<-- custom is now the new option for the tooltip position
/** #type {Chart.Tooltip} */
var tooltip = this;
/* ... */
return {
x: eventPosition.x,
y: eventPosition.y
};
}
export default {
extends: Bar,
props: ['options', 'chartData'],
data() {
return{
chart: this.chartData
}
},
watch: {
//Renders the chart
chartData(){
this.renderChart(this.chartData, this.options)
}
},
}
</script>
I was expecting chart.update() to update but it keeps returning undefined.
The first component you posted refers to this.chartData(), however there is no chartData property on that component. You can force an update by create a ref, then accessing this.$refs.<yourref>.update() within your update handler.

How to show more than one "dataMax" in Highcharts?

Currently, I'm showing a max point in the line chart. But I want to change dataMax to top 5 max value points in chart.How can I achieve this in Highcharts?
var defaultData = 'urlto.csv';
var urlInput = document.getElementById('fetchURL');
var pollingCheckbox = document.getElementById('enablePolling');
var pollingInput = document.getElementById('pollingTime');
function createChart() {
Highcharts.chart('closed5', {
chart: {
type: 'area',
zoomType: 'x'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
style: {},
formatter: function() {
if (this.y === this.series.dataMax) {
return this.y;
}
}
}
}
},
title: {
text: 'Chart for charting'
},
data: {
csvURL: urlInput.value,
enablePolling: pollingCheckbox.checked === true,
dataRefreshRate: parseInt(pollingInput.value, 10)
}
});
if (pollingInput.value < 1 || !pollingInput.value) {
pollingInput.value = 1;
}
}
urlInput.value = defaultData;
// We recreate instead of using chart update to make sure the loaded CSV
// and such is completely gone.
pollingCheckbox.onchange = urlInput.onchange = pollingInput.onchange = createChart;
// Create the chart
createChart();
As #ewolden rightly noticed, you can sort your data and show only the five highest values:
var data = [11, 22, 33, 44, 55, 66, 15, 25, 35, 45, 55, 65],
sortedData = data.slice().sort(function(a, b){
return b - a
});
Highcharts.chart('container', {
series: [{
data: data,
dataLabels: {
enabled: true,
formatter: function() {
if (sortedData.indexOf(this.y) < 5) {
return this.y;
}
}
}
}]
});
Live demo: http://jsfiddle.net/BlackLabel/xkf2w5tb/
API: https://api.highcharts.com/highmaps/series.mapbubble.dataLabels.formatter
As far as I know formatter callback is the way to format the data labels. If you want to show the top N points you should sort the data in a new array and pull the top 5 values. This is an example of how to clone and sort the array and extract the top 5 elements in the formatter call.
let data = [32, 10, 20, 99, 30, 54, 85, 56, 11, 26, 15, 45, 55, 65];
//Copy the array
let temp = data.slice();
// Sort the temp array in descending order
temp.sort((a, b) => b - a);
Highcharts.chart('closed5', {
chart: {
type: 'area',
zoomType: 'x'
},
title: {
text: 'Chart for charting'
},
series: [{
data: data,
dataLabels: {
enabled: true,
formatter: function() {
if (temp.indexOf(this.y) < 5) {
return this.y;
}
},
},
}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="closed5"></div>

Categories

Resources