Add custom values to Legend in lightningchart - lightningchart

I can create legends like below
Is there any way , I can add custom text dynamically in the place of Bollinger band ? For example I want to show live price every second in legend.
Also how do I programatically enable and disable a legend.
Thank you

You can store the legendbox entry returned by the legendBox.add() method. This entry has a method entry.setText() that can be used to set the text of the legend box entry to be what ever you want.
const legendBox = chart.addLegendBox()
const entry = legendBox.add(series, undefined, 'Legend Box')
entry.setText('Custom text here')
By storing the entry reference you can call the setText method when ever you want to update the text.
See the below example in which the legend box entry text is updated every time new data is added.
// Extract required parts from LightningChartJS.
const {
lightningChart,
DataPatterns,
Themes
} = lcjs
// Import data-generator from 'xydata'-library.
const {
createProgressiveTraceGenerator
} = xydata
// Create a XY Chart.
const chart = lightningChart().ChartXY({
// theme: Themes.dark
})
// Create progressive line series.
const series = chart.addLineSeries({
dataPattern: DataPatterns.horizontalProgressive
})
const lb = chart.addLegendBox()
lb.setPosition({
x: 50,
y: 50
})
const entry = lb.add(series, undefined, 'Legend Box')
// Generate traced points stream using 'xydata'-library.
createProgressiveTraceGenerator()
.setNumberOfPoints(1000)
.generate()
.toStream()
.forEach(data => {
series.add(data)
entry.setText(`Custom text: ${series.getLastPoint().y.toFixed(1)}`)
})
<script src="https://unpkg.com/#arction/xydata#1.4.0/dist/xydata.iife.js"></script>
<script src="https://unpkg.com/#arction/lcjs#2.2.1/dist/lcjs.iife.js"></script>
You can disable the legend box by calling legendbox.dispose(). This will remove the legendbox completely. To then enable the legendbox again you can call legendbox.restore() which will restore the legendbox as it was.

Related

Hiding legendbox title in lightningchart

How do we hide the title in legendbox and remove the padding on top.
const lb = chart.addLegendBox()
lb.setPosition({
x: 50,
y: 50
})
const entry = lb.add(series, undefined, 'Legend Box')
If I replace 'Legend Box' above I get undefined group as title.
At this time there is no way to delete the title of LegendBox.
Some things you can try:
Pass empty string ' ' instead of undefined
Try negative paddings, margins
Create your own LegendBox (make a Layout UIElement, add CheckBox elements to it, attach CheckBoxes to series using series.attach)
In v3.0.0 release (late this month), there will be proper API for LegendBox title.
EDIT
General syntax of creating Layout, CheckBox and attaching it to a series:
const customLegendBox = chart.addUIElement(UILayoutBuilders.Column)
const entry1 = customLegendBox.addElement(UIElementBuilders.CheckBox)
mySeries.attach(entry1)

In created:, my method doesn't work perfectly

I'm trying to make a simple vue.js & d3.js code. In the code, I want to plot some charts. For that, I'm trying to make some spaces for charts, by defining a method('add_svg') and run the method in created.
But, the method('add_svg') doesn't work what i intended. I had checked that the method was working, by inserting console.log('Running') for the first part of the method.
I could saw the message, 'Running', but the svg_space, i wanted to insert, wasn't inserted.
But when I UPDATE charts with same method in computed: part, it works.
In the computed: part, it generates some spaces several times, which means that it's working and the method has no problem.
Why is that?
Below is my code:
// GIVES CONSOLE.LOG MESSAGE('RUNNING') BUT DOES NOT APPEND SVG
created () {
console.log("")
this.add_svg() // append svg for chart
this.plot([0, 0]) // basic plot with value = [0, 0]
},
...
// SAME METHOD, BUT IN HERE, IT GIVES ME WHAT I WANTED.
// BUT TO INITIALIZE, I WANT TO RUN THE METHOD IN created: part, not in computed
computed () {
this.add_svg()
this.plot( datum )
}
...
methods: {
add_svg: function () {
console.log("Adding some space for chart")
d3.select('.chart_test2')
.append('svg')
.attr('class', 'svg_chart_test2')
.attr('width', '10px')
.attr('height', '10px')
},
other methods...
}
In Vue, you have to draw d3 charts on the mounted hook, rather than the created hook. You can't draw the chart if the page is not rendered - which is what happens when you use the created hook.
mounted () {
this.add_svg() // append svg for chart
this.plot([0, 0]) // basic plot with value = [0, 0]
}

My own defined colors for graphs in Kintone

I'd like to set my own defined colors for graphs that appear in Kintone.
I've found out for pie charts, you can upload the below CSS code to the App to have some areas of the pie to become a color of your choice.
.highcharts-series-group .highcharts-series path:nth-of-type(even){
fill:pink;
}
What I'd really like to do though, is apply the same thing to the Line charts in kintone.
I've tried the below CSS:
.highcharts-tracker path {
fill: red;
}
This only changes the points plotted on the graph, but not the lines in between the points.
How can I identify the lines in this graph so that I can end up with lines of the color of my choice??
Updated 6/24/18
Like you mentioned, the code that I showed you displays only on the record detail page. However, if you just make the process to run on the record list event "app.record.index.show", you can show the graph on the top of the record list page.
Also, it will be better to use kintone.app.getHeaderSpaceElement() to append a graph on the record list page.
The following page is an example of how to append something on the record list page using the kintone.app.getHeaderSpaceElement():
kintone developer network - kintone x OpenStreetMap
https://developer.kintone.io/hc/en-us/articles/115003669514
The following page is about the record list header element:
kintone developer network - Get Record List Header Element
https://developer.kintone.io/hc/en-us/articles/213148937-Get-Record-List#getHeaderSpaceElement
=================================================
Original Reply
It's better off not editing the DOM because it might not work after any kintone updates. I recommend creating a custom graph using Chart.js, a javscript library. The following page helps you how to do so.
Example Code
(function() {
"use strict";
// Events for adding and editing records
var eventsCreateShow = ['app.record.create.show', 'app.record.edit.show',
'app.record.index.create.show', 'app.record.index.edit.show'];
kintone.events.on(eventsCreateShow, function(event) {
// Hide the "Chart" Group field
kintone.app.record.setFieldShown('Chart', false);
});
// Display the chart on the record details page (PC and mobile)
var eventsDetailShow = ['app.record.detail.show', 'mobile.app.record.detail.show'];
kintone.events.on(eventsDetailShow, function(event) {
var record = event.record;
var data = {
labels: ["Language Arts", "Math", "Science", "Social Studies", "P.E."],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(0,140,232,.4)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: [
record['language_arts']['value'],
record['math']['value'],
record['science']['value'],
record['social_studies']['value'],
record['pe']['value']
]
}
]
};
// Set Chart.js options
var options = {
scaleShowLine: true,
angleShowLineOut: true,
scaleShowLabels: true,
scaleBeginAtZero: true,
angleLineColor: "rgba(0,0,0,.1)",
angleLineWidth: 1,
pointLabelFontFamily: "'Arial'",
pointLabelFontStyle: "normal",
pointLabelFontSize: 16,
pointLabelFontColor: "#666",
pointDot: true,
pointDotRadius: 5,
pointDotStrokeWidth: 1,
pointHitDetectionRadius: 20,
datasetStroke: true,
datasetStrokeWidth: 3,
datasetFill: true,
responsive: true
};
var elRadar;
var elCanvas = document.createElement('canvas');
elCanvas.id = 'canvas';
// Display radar chart onto the Blank space
// Edit display size depending on PC or mobile
if (event.type === 'mobile.app.record.detail.show') {
elRadar = kintone.mobile.app.getHeaderSpaceElement();
elCanvas.style.position = 'relative';
elCanvas.style.top = '10px';
elCanvas.style.left = '10px';
elCanvas.height = '300';
elCanvas.width = '300';
} else {
elRadar = kintone.app.record.getSpaceElement('Radar');
elCanvas.height = '400';
elCanvas.width = '400';
}
elRadar.appendChild(elCanvas);
var myChart = new Chart(elCanvas.getContext("2d")).Radar(data, options);
});
})();
Ref:kintone developer network - Display radar charts with chart.js
https://developer.kintone.io/hc/en-us/articles/115006413388-Display-radar-charts-with-chart-js
I hope this helps

How to dynamically alter point radius and style of JSON path in d3?

I need help in dynamically "highlighting" cities on a world map, created using D3 and geoJSON.
I'm working on a spinning globe with 295 city-markers on it. Every 300 millisec, one of these cities need to "be highlighted", meaning 1) change its color and 2) increase its radius (and then stay that way). This gist shows the visual so far: gist example
Steps taken so far:
1) I started with "circle" elements in d3: highlighting was easily done by changing their class (and using CSS styles) and radius. However: the circles remained visible on the "backside" of the globe...
2) To solve the "no circles on back of earth" problem, this post showed me that JSON paths would help: http://bl.ocks.org/PatrickStotz/1f19b3e4cb848100ffd7.
I have now rewritten the code with these paths, and there is correct clipping of the markers on the back of the earth, but now I am stuck in dynamically accessing the radius and style of each city...
Question about changing the radius:
I understand that using path.pointRadius() I can alter the radius of the city markers. However, I want to do this dynamically (every 300msec), and only on a subselection of the markers each time. And that's where I get stuck...
Question about changing the style:
Also I would like to change the color, but assigning styles to the paths confuses me about how to access the JSON "Point" and "path" elements...
Code snippet showing my failed CSS styles attempt:
svg.append('g')
.selectAll("path")
.data(data,function(d,i){ return d.id })
.enter()
.append("path")
.datum(function(d) {
return {
type: "Point",
coordinates: [d.lon, d.lat],
class: "nohighlight" //MY ATTEMPT AT CHANGING CLASS... Not working...
}; })
.attr("class","city") //this class is assigned to the "correct" paths. Can I access them individually??
.attr("d", pathproj);
Code snippet showing the time loop in which the highlighting needs to happen:
//Highlighting the cities one by one:
var city_idx = 0; //data.id starts at 1
//Every 300 msec: highlight a new city:
var city_play = setInterval(function() {
city_idx++;
var filtered = data.filter(function(d) {
return d.id === city_idx;
});
// CHANGE CLASS?
// CHANGE RADIUS?
//Stop when all cities are highlighted
if(city_idx>=geo_data.length){
clearInterval(city_play) //terminates calls to update function within setInterval function.
};
}, 300); // end timer city play setInterval
Full code in block builder:
blockbuilder - globe and city markers
Please do let me know if I can clarify further!
We can do it this way:
To all path belonging to cities give a class
.selectAll("path")
.data(data,function(d,i){ return d.id })
.enter()
.append("path")
.classed("city", true) <--- so all cities point will have class city
Next in the timer block change radius and class dynamically like this:
var city_play = setInterval(function() {
city_idx++;
// Control the radius of ALL circles!
pathproj.pointRadius(function(d,i) {
//your biz logic
if (i < city_idx){
return 4
} else
return 2
});
// CHANGE CLASS?
// CHANGE RADIUS?
//select all elements with class city
d3.selectAll(".city").attr("class",
function(d, i){
if (i < city_idx){
return "city highlight"
} else
return "city"
}).attr("d", pathproj)
var len = d3.selectAll(".city").data().length;
console.log(city_idx, len)
//Stop when all cities are highlighted
if(city_idx>=len){
clearInterval(city_play) //terminates calls to update function within setInterval function.
};
}, 300);
working code here

how to select feature by drawing a line in openlayers?

There is one option in openlayers selecting features under the box. But, I want to select the features when I draw line (draw with shift key down-free hand drawing). In my script I already implemented drawing and selecting options. I can draw line and select (multiple) features independently. Now, I want to merge this two. I want to select those features data which are touched by my drawn line. Is there any sample example available?
Here, I have given sample code -
//Selection property---------------------------------------
var selectControl = new OpenLayers.Control.SelectFeature(
[vectorLayer],
{
clickout: true, toggle: true,
multiple: true, hover: false,
toggleKey: "ctrlKey", // ctrl key removes from selection
multipleKey: "shiftKey" // shift key adds to selection
}
);
map.addControl(selectControl);
selectControl.activate();
var draw = new OpenLayers.Control.DrawFeature(
vectorLayer, OpenLayers.Handler.Path,
{displayClass: "olControlDrawFeaturePoint", title: "Draw Features", handlerOptions: {holeModifier: "altKey"}}
);
Thanks, in advance.
You have to register event "sketchcomplete" that will run over all features in layer-bo-be-selected and check if it has shared geometry with line sketched.
Something like this, unfortunately I can't test it now.
vectorLayer.events.register('sketchcomplete', vectorLayer, sketchCompleteFunc);
function sketchCompleteFunc(obj) {
for (var i=0;i<layer-to-be-selected.features.length;i++) {
if (layer-to-be-selected.features[i].geometry.intersects(obj.geometry)) {
selectControl.select(layer-to-be-selected.features[i])
}
}
}

Resources