Right now my graph's label is placed in a default position, but my label texts are rather long and its sticking out from the graph.
If possible, I want to place it so that the labels don't stick out from the graph.
Pic of Current situation & Ideal graph
Or if the above is not possible, I want to fix the visible labels. Is this possible?
right now, the "best" label gets lost/hidden when the graph width is reduced. The "too much" label also gets lost when the width is largely reduced.
I have been searching all over stackoverflow and amcharts website but I can't seem to find a good solution.
Is there any way to solve either of the problems...?
// tried these but doesnt work for what I want to do
va.labelOffset = -5;
va.position = "bottom";
va.inside = false;
full code in JSfiddle
In order to keep the chart from hiding the labels on resize, you need to disable the valueAxis' autoGridCount and set the gridCount to the number of tick marks you want to see. You'll also need to remove the labelFrequency setting.
va.autoGridCount = false;
va.gridCount = 3;
//va.labelFrequency = 5;
As for label positioning, you are limted to rotating and vertical offsets out of the box. As a workaround, you can position the labels by modifying the SVG nodes directly through the drawn event, for example:
// prior to chart.write
chart.addListener("drawn", function(e) {
var textNodes = e.chart.valueAxes[0].labelsSet.node.childNodes;
var transform;
//Position "too little"
transform = parseTransform(textNodes[0].getAttribute('transform'));
transform.translate[0] = parseFloat(transform.translate[0]) + 25;
textNodes[0].setAttribute('transform', serializeTransform(transform));
// Position "too much"
transform = parseTransform(textNodes[2].getAttribute('transform'));
transform.translate[0] = parseFloat(transform.translate[0]) - 25;
textNodes[2].setAttribute('transform', serializeTransform(transform));
});
// ...
// from http://stackoverflow.com/questions/17824145/parse-svg-transform-attribute-with-javascript
function parseTransform(a) {
var b = {};
for (var i in a = a.match(/(\w+\((\-?\d+\.?\d*e?\-?\d*,?)+\))+/g)) {
var c = a[i].match(/[\w\.\-]+/g);
b[c.shift()] = c;
}
return b;
}
//serialize transform object back to an attribute string
function serializeTransform(transformObj) {
var transformStrings = [];
for (var attr in transformObj) {
transformStrings.push(attr + '(' + transformObj[attr].join(',') + ')');
}
return transformStrings.join(',');
}
Updated fiddle
Related
I have a requirement to show data labels of two graphs on the same axes.
Only when they intersect, one of the two labels won't show. This can be demonstrated below:
As you can see on the 2nd, 5th and 6th columns from the left with values 0%, 7% and 8% respectively
only the orange line values are shown but the blue column values are missing.
This is the final html of the graph after rendering:
So data-datapoint-id 142, 145 and 146 are missing from the html.
I tried using the plotArea.dataLabel.renderer function as a manipulation of what was proposed here but nothing changed, still not rendering.
Anyone encountered a similar problem? Is that a sapui5 issue or can it be fixed by manually inserting the labels into the HTML if so how?
Thanks,
Ori
Using SVG text and jQuery I managed to manually insert the labels into the top middle of the blue rectangle columns.
This is the result, not perfect but works:
and this is the code:
chart.setVizProperties({
plotArea: {
dataLabel: {
formatString: {'פחת כללי': FIORI_PERCENTAGE_FORMAT_2},
renderer: function (oLabel) {
// Create empty text node to be returned by the function such that the label won't be rendered automatically
var node = document.createElement("text");
if (oLabel.ctx.measureNames === "כמות פחת כללי") {
var kamutLabelIdx = oLabel.ctx._context_row_number;
// Use jQuery and SVG to manipulate the HTML
var kamutLabelQuery = '[data-id=\"' + kamutLabelIdx + '\"]';
var kamutColumn = $(kamutLabelQuery)[0];
// Create text element as child of the column
kamutColumn.innerHTML += "<text>" + oLabel.text + "</text>";
var labelNode = $(kamutLabelQuery += ' text');
// Set the label position to be at the middle of the column
const labelLength = 60;
const xPos = (labelLength + oLabel.dataPointWidth) / 2;
const yPos = oLabel.styles['font-size'];
labelNode.attr({
"textLength" : labelLength,
"x" : xPos,
"y" : yPos,
"font-size" : yPos
});
return node;
}
}
}
}
});
The oLabel parameter of the renderer function provides useful info about the data label to be created:
I still wonder if that's a bug with sapui5 vizframe and if there is a simpler way to do this.
Please let me know of your thoughts
I have used am4charts.XYCursor(), which shows cursor values on Y & X axes. I wish to hide / disable values showing on Y axis.
chart.cursor.lineY.disabled = true;
CodePen:
https://codepen.io/pthakkar/pen/rgLqYY
/* Create a cursor */
chart.cursor = new am4charts.XYCursor();
/* Configure cursor lines */
chart.cursor.lineX.stroke = am4core.color("#8F3985");
chart.cursor.lineX.strokeWidth = 4;
chart.cursor.lineX.strokeOpacity = 0.2;
chart.cursor.lineX.strokeDasharray = "";
chart.cursor.lineY.disabled = true;
I expect the cursor values appearing on the Y axis (in black background) to disappear.
The cursor values are controlled by another properties called Axis Tooltips and they are configured per axis, and not per cursor (as it would be assumed). Calling:
axis.cursorTooltipEnabled = false;
should disable the tooltip. See the modified codepen for a working solution.
So what I want to happen is that when viewing the Span the text is normal but as you scroll down it starts moving until it looks like such:
Before the effect:
While the effect occurs:
The header is represented by spans for each letter. In the initial state, the top pixel value for each is 0. But the idea as mentioned is that that changes alongside the scroll value.
I wanted to keep track of the scroll position through JS and jQuery and then change the pixel value as needed. But that's what I have been having trouble with. Also making it smooth has been another issue.
Use the mathematical functions sine and cosine, for characters at even and odd indices respectively, as the graphs of the functions move up and down like waves. This will create a smooth effect:
cos(x) == 1 - sin(x), so in a sense, each character will be the "opposite" of the next one to create that scattered look:
function makeContainerWiggleOnScroll(container, speed = 0.01, distance = 4) {
let wiggle = function() {
// y-axis scroll value
var y = window.pageYOffset || document.body.scrollTop;
// make div pseudo-(position:fixed), because setting the position to fixed makes the letters overlap
container.style.marginTop = y + 'px';
for (var i = 0; i < container.children.length; i++) {
var span = container.children[i];
// margin-top = { amplitude of the sine/cosine function (to make it always positive) } + { the sine/cosine function (to make it move up and down }
// cos(x) = 1 - sin(x)
var trigFunc = i % 2 ? Math.cos : Math.sin;
span.style.marginTop = distance + distance * trigFunc(speed * y)/2 + 'px';
}
};
window.addEventListener('scroll', wiggle);
wiggle(); // init
}
makeContainerWiggleOnScroll(document.querySelector('h2'));
body {
height: 500px;
margin-top: 0;
}
span {
display: inline-block;
vertical-align: top;
}
<h2>
<span>H</span><span>e</span><span>a</span><span>d</span><span>e</span><span>r</span>
</h2>
Important styling note: the spans' display must be set to inline-block, so that margin-top works.
Something like this will be the core of your JS functionality:
window.addEventListener('scroll', function(e) {
var scrl = window.scrollY
// Changing the position of elements that we want to go up
document.querySelectorAll('.up').forEach(function(el){
el.style.top = - scrl/30 +'px';
});
// Changing the position of elements that we want to go down
document.querySelectorAll('.down').forEach(function(el){
el.style.top = scrl/30 +'px';
});
});
We're basically listening in on the scroll event, checking how much has the user scrolled and then act upon it by offsetting our spans (which i've classed as up & down)
JSBin Example
Something you can improve on yourself would be making sure that the letters wont go off the page when the user scrolls a lot.
You can do this with simple math calculation, taking in consideration the window's total height and using the current scrollY as a multiplier.
- As RokoC has pointed out there is room for performance improvements.Implement some debouncing or other kinds of limiters
I'm trying to detect the right position of a scrollbar-thumb. Can somebody please explain if this is possible. The scrollbar thumbnail does not have fixed width. I'm using nw.js, ES6 and jQuery library.
The following is a simplified extraction of my code.
class C {
constructor() {
win.on('resize', this._resize.bind(this));
$('#divId').on('scroll', this._scroll.bind(this));
}
_getXScrollbarThumbPos() {
let lpos = $('#divId').scrollLeft();
let rpos = lpos + SCROLLBAR_THUMBNAIL_WIDTH; // FIXME how can I get the scrollbarThumbnailWidth
return rpos;
}
_resize() {
let x = this._getXScrollbarThumbPos();
//..
}
_scroll() {
let x = this._getXScrollbarThumbPos();
//..
}
}
The resize and scroll listener work ok, the only bottleneck is how to determine the width of the scrollbar-thumbnail. win is the nw.js wrapper of the DOM's window, see here (initialization is not shown here, as it is not relevant for the question).
This is the solution I've eventually used. While I haven't found a way to directly obtain any dimensions of the right scrollbar-thumb position due to the dynamic width (for which I've also have not detected a way to calculate this), I have actually been able to solve the problem; By determining the width of the total content (i.e. the viewable + overflowing content), and subtracting both the viewable content width and scrolled to the left content-width, we can determine uttermost right position of the scrollable content, within the viewport, which (neglecting any possible border widths) equals the right position of the scollbar-thumb.
class C {
constructor() {
win.on('resize', this._resize.bind(this));
$('#divId').on('scroll', this._scroll.bind(this));
}
_getXScrollbarThumbPos() {
// width of the content + overflow
let totalWidth = $('#divId').scrollWidth;
// width of the visible (non overflowing) content
let viewWidth = $('#divId').width();
// the amount of pixels that the content has been scrolled to the left
let lpx = document.getElementById('#divId').scrollLeft;
// the amount of pixels that are hidden to right area of the view
let rpx = totalWidth - viewWidth - lpx;
// represents the right position of the scrollbar-thumb
console.log(rpx);
return rpx;
}
_resize() {
let x = this._getXScrollbarThumbPos();
//..
}
_scroll() {
let x = this._getXScrollbarThumbPos();
//..
}
}
What is the best way to restore the scroll position in an HTML document after the screen has been rotated? (This is in a Cocoa Touch UIWebView, but I think it's a problem everywhere.) The default behavior seems to restore the y-offset in pixels, but since the text has been reflowed this is now a different position in the document.
My initial thought is to:
Pepper the document with invisible, uniquely-id'ed elements.
Before rotation, search for the element e whose y-offset is closest to the scroll offset.
After rotation, update the scroll offset to e's new y-offset.
Even if that works, I'd prefer not to insert a bunch of crud into the document. Is there a better way?
Here's a diagram to clarify the problem. Restoring the original y-offset does not produce the intended result because more text fits on a line in landscape mode.
Not pretty but it works. This requires there to be span tags throughout the document text.
// Return the locator ID closest to this height in pixels.
function findClosestLocator(height) {
var allSpans = document.getElementsByTagName("span");
var closestIdx = 0;
var closestDistance = 999999;
for(var i = 0; i < allSpans.length; i++) {
var span = allSpans[i];
var distance = Math.abs(span.offsetTop - height);
if(distance < closestDistance) {
closestIdx = i;
closestDistance = distance;
}
}
return allSpans[closestIdx].id;
}
After rotation, document.getElementById(spanId).offsetTop is the new y-offset, where spanId is the result of findClosestLocator() before rotation.
Conceptually the problem isn't so hard to think about. You have scroll events, rotation events, and variables. I would track the scrollTop position on the document.body DOM node on the scroll event. Reapply it with the orientation event fires.
Something like this perhaps.
// Track position
var pos;
// On scroll update position
document.body.addEventListener("scroll", function() {
pos = document.body.scrollTop;
}, true);
// On rotation apply the scroll position
window.addEventListener("orientationchange", function() {
document.body.scrollTop = pos;
}, true);