Tickformatter not performing as expected in latest version of Flot - jquery-plugins

In our previous version of Flot, the following tickformatter function worked fine. It displayed the value and used the class correctly.
yaxis: {
tickFormatter: function(v, axis) {
return "<span class='axisLabel'>" + v + "%</span>";
}
In the latest version (v. 0.7) it renders the tags literally so next to the graph I see a something like
<span class='axisLabel'>50%</span>
where the y axis tick labels should be. I should only be seeing a list of percentages.
I've done as much debugging as I can but haven't found out what is causing this. Any ideas would be appreciated.

This is due to a recent "improvement" in how the labels are treated, I think. From README.md in the development version:
Axis labels are now drawn with canvas text with some parsing to
support newlines. This solves various issues but also means that they
no longer support HTML markup, can be accessed as DOM elements or
styled directly with CSS.
More specifically, it seems that
function insertAxisLabels() {...}
was replaced by
function drawAxisLabels(){...}
at some point. The former used to place axis labels as a bunch of <div> elements, as follows:
<div class="tickLabels" style="font-size:smaller">
<div class="xAxis x1Axis" style="color:#545454">
<div class="tickLabel" style="position:absolute;text-align:center;left:-14px;top:284px;width:75px"><em>0</em></div>
[... div elements for other labels...]
</div>
</div>
That allowed one to use html code in the tickFormatter. In the latest version, all this is gone, and the labels are added to the canvas directly via
ctx.fillText(your_label, x, y);
No html formatting tags therefore work anymore. Things that used to be simple, like styling the tick labels or turning them into links, are now less straightforward. Maybe flot developers can shed some light on what is the best way to achieve the same functionality in the new version.
I am using flot mostly for barcharts. One (ugly) workaround that seems to work for me is to replace the entire drawAxisLabels function in the newest jquery.flot.js by insertAxisLabels function from the stable version (after renaming it to drawAxisLabels). I additionally have to set manually labelWidth in xaxis options of my plots since otherwise the width of the plots is calculated incorrectly.

function formatter(val, axis) {
return "<span style='font-weight: bold'>" + val / 1000000 + "m</span>";
}
var usersData = { color: "#00FF55", data: [[1, 900000], [2, 926000], [3, 959000], [4, 1056000], [5, 1242300]] };
$(document).ready(function() {
$.plot($("#UserGraph"), [usersData], { xaxis: { ticks: [] }, yaxis: { tickFormatter: formatter } });
});
I could remove the style and the numbers go back to normal non-bold numbers.

Related

Plotly.js, show tooltips outside of chart container

I need to implement a plotly.js chart on a page with a very restricted width. As a result, a tooltip is partially cut. Is it possible to cause tooltip not to be limited by plotly.js container size?
My code example at codepen: https://codepen.io/anatoly314/pen/gOavXzZ?editors=1111
//my single trace defined as following but it's better to see example at codepen
const yValue1 = [1000];
const trace1 = {
x: [1],
y: yValue1,
name: `Model 1`,
text: yValue1.map(value => Math.abs(value)),
type: 'bar',
textposition: 'outside'
};
It is, by design, not possible for any part of the chart to overflow its container.
I would say it is wrong to say that by design this is not possible! It is a bit hacky, but when you add the following lines, it shows the label outside of svg:
svg.main-svg,svg.main-svg *
{
overflow:visible !important;
}
The answer given by rokdd works. However the css selector should be more specific, otherwise it's natural that you will introduce subtle bugs (particularly if you need to scroll the content where the plotly chart is contained).
If we look at the DOM tree constructed by Plotly, we find that the tooltips are created inside the <g class="hoverlayer"></g> element (which is a direct child of one of the three <svg class="main-svg"></svg>). So that parent (that svg.main-svg element) is only one that needs to affected.
The ideal css selector in this case would be the :has selector. However it's still not supported (as of 2022): https://css-tricks.com/the-css-has-selector/
So the next simplest thing is to use a little bit of javascript right after we call Plotly.newPlot:
// get the correct svg element
var mainSvgEl = document.querySelector('#positive g.hoverlayer').parentElement;
mainSvgEl.style['overflow'] = 'visible';
Or in a more generic way (works for any chart):
Array.from(document.querySelectorAll('g.hoverlayer')).forEach(hoverEl => {
let mainSvgEl = hoverEl.parentElement;
mainSvgEl.style['overflow'] = 'visible';
});

How to apply brushing on a dynamically growing dataset?

I have a dynamically growing timeseries I need to display in a zoomable/panable chart.
Try it out here (in fact: my first jsFiddle ever :) ) :
https://jsfiddle.net/Herkules001/L12k5zwx/29/
I tried to do it the same way as described here: https://dc-js.github.io/dc.js/examples/replacing-data.html
However, each time the chart updates, the zoom and filter are lost on the focus chart. (The brush is preserved on the range chart however.)
How can I add data without resetting the views and losing the zoom?
var chart = dc.lineChart("#test");
var zoom = dc.lineChart("#zoom");
//d3.csv("morley.csv", function(error, experiments) {
var experiments = d3.csvParse(d3.select('pre#data').text());
experiments.forEach(function(x) {
x.Speed = +x.Speed;
});
var ndx = crossfilter(experiments),
runDimension = ndx.dimension(function(d) {return +d.Run;}),
speedSumGroup = runDimension.group().reduceSum(function(d) {return d.Speed * d.Run / 1000;});
chart
.width(768)
.height(400)
.x(d3.scaleLinear().domain([6,20]))
.brushOn(false)
.yAxisLabel("This is the Y Axis!")
.dimension(runDimension)
.group(speedSumGroup)
.rangeChart(zoom);
zoom
.width(768)
.height(80)
.x(d3.scaleLinear().domain([6,20]))
.brushOn(true)
.yAxisLabel("")
.dimension(runDimension)
.group(speedSumGroup);
zoom.render();
chart.render();
var run = 21;
setInterval(
() => {
var chartfilter = chart.filters();
var zoomfilter = zoom.filters();
chart.filter(null);
zoom.filter(null);
ndx.add([{Expt: 6, Run: run++, Speed: 100 + 5 * run}]);
chart.x(d3.scaleLinear().domain([6,run]));
zoom.x(d3.scaleLinear().domain([6,run]));
chart.filter([chartfilter]);
zoom.filter([zoomfilter]);
chart.render();
zoom.render();
},
1000);
//});
In this case, if you are just adding data, you don't need to do the complicated clearing and restoring of filters demonstrated in the example you cited.
That part is only necessary because crossfilter.remove() originally would remove the data that matched the current filters. An awkward interface, almost never what you want.
If you're only adding data, you don't have to worry about any of that:
setInterval(
() => {
ndx.add([{Expt: 6, Run: run++, Speed: 5000 + 5 * run}]);
chart.redraw();
zoom.redraw();
},
5000);
Note that you'll get less flicker, and decent animated transitions, by using redraw instead of render. I also added evadeDomainFilter to avoid lines being clipped before the edge of the chart.
Fork of your fiddle
Removing data
If you use the predicate form of crossfilter.remove() you don't have to worry about saving and restoring filters:
ndx.remove(d => d.Run < run-20);
However, this does expose other bugs in dc.js. Seems like elasticY does not work, similar to what's described in this issue. And you get some weird animations.
Here's a demo with remove enabled.
In the end, dc.js has some pretty neat features, and there is usually a way to get it to do what you want, but it sure is quirky. It's a very complicated domain and in my experience you are going to find some of these quirks in any fully featured charting library.
Update: I fixed the replacing data example, that one is just ndx.remove(() => true) now.
zooming issues
As Joerg pointed out in the comments,
when the chart is not zoomed, it would be nice to have it also grow to show new data as it arrives
the X domain was clipped or even reversed if the focus reached outside the original domain of the chart
We can address these issues by adding a preRedraw event handler. That's the ideal place to adjust the domain; for example you can implement elasticX manually if you need to. (As you'll see in a second, we do!)
First, a naive attempt that's easy to understand:
chart.on('preRedraw', () => {
chart.elasticX(!zoom.filters().length);
});
We can turn elasticX on and off based on whether the range chart has an active filter.
This works and it's nice and simple, but why does the chart get so confused when you try to focus on a domain that wasn't in the original chart?
Welp, it records the original domain (source). So that it can restore to that domain if the focus is cleared, and also to stop you from zooming or panning past the edge of the graph.
But notice from the source link above that we have an escape hatch. It records the original domain when the X scale is set. So, instead of setting elasticX, we can calculate the extent of the data, set the domain of the scale, and tell the chart that the scale is new:
chart.on('preRedraw', () => {
if(!zoom.filters().length) {
var xExtent = d3.extent(speedSumGroup.all(), kv => kv.key);
chart.x(chart.x().domain(xExtent));
}
});
New fiddle with zooming issues fixed.
There is still one glitch which Joerg points out: if you are moving the brush while data comes in, the brush handles occasionally will occasionally stray from the ends of the brush. In my experience, these kinds of glitches are pretty common in D3 (and dynamic charting in general), because it's difficult to think about data changing during user interaction. It probably could be fixed inside the library (perhaps an interrupted transition?) but I'm not going to get into that here.

plotly.js legend overlap the graph

Please see example screenshot - I cannot reproduce except on this site, it seems to be some conflict with the css but any ideas what?
Normally, plotly moves the legend at the top if there is not enough horizontal space. However, this example shows that the legend overlaps the graph. Even if I make the legend orientation horizontal, it still overlaps the graph.
Do you have any ideas why it could happen?
Adjusting the legend position in normalized coordinates should help. See also here.
I.e.:
layout = go.Layout(
legend={"x" : 1.2, "y" : 1}
)
Placing the legend outside of the plot works for me:
var layout = {
showlegend: true,
legend: {
x: 1,
}
};
Fixed by a css wizard https://tiki.org/item6567 (Luci):
.js-plotly-plot .plotly .main-svg {overflow: visible}
.js-plotly-plot .plotly .main-svg .legend {transform: translate(640px, 100px)}

Is an NVD3 Line Plot with Markers Possible?

I'm making an NVD3 line plot that will have significantly improved clarity if I can get markers to show for each data point instead of just the line itself. Unfortunately, I haven't been able to find an easy way to do this with NVD3 yet. I also considered using a scatter plot, but I couldn't figure out how to show connecting lines between the points. A third option I considered was to overlay a line and scatter plot, but this would show each series twice in the legend and may cause other unnecessary visual complications.
Is there a way to elegantly pull this off yet? Sample code of my formatting technique is listed below, but the 'size' and 'shape' attributes in test_data have no effect on the line plot with the current code.
test_data = [ { key: 'series1',
values: [
{ x: 1, y: 2.33, size:5, shape:"circle" },
{ x: 2, y: 2.34, size:5, shape:"circle" },
{ x: 3, y: 2.03, size:5, shape:"circle" },
] } ];
nv.addGraph(function() {
var test_chart = nv.models.lineChart();
test_chart.xAxis.axisLabel('Sample Number');
test_chart.yAxis
.axisLabel('Voltage (V)')
.tickFormat(d3.format('.02f'));
d3.select('#test_plot')
.datum(test_data)
.transition().duration(500)
.call(test_chart);
nv.utils.windowResize(test_chart.update);
return test_chart;
});
I also wanted to add markers in a project I was working on. Here is a solution my partner and I found.
First, you have to select all of the points in your chart and set the fill-opacity to 1:
#my-chart .nv-lineChart circle.nv-point
{
fill-opacity: 1;
}
Now your points will be visible. To adjust the size of each point you need to modify each one's "r" (for radius) attribute. This isn't a style so you can't do it with css. Here is some jQuery code that does the job. The 500 millisecond delay is so the code will not run before the chart is rendered. This snippet sets the radius to 3.5:
setTimeout(function() {
$('#my-chart .nv-lineChart circle.nv-point').attr("r", "3.5");
}, 500);
This puzzled me until I got help from the community:
css styling of points in figure
So here is my solution, based on css:
.nv-point {
stroke-opacity: 1!important;
stroke-width: 5px!important;
fill-opacity: 1!important;
}
If anyone has come here from rCharts, below is a rmarkdown template to create an nPlot with both lines and markers:
```{r 'Figure'}
require(rCharts)
load("data/df.Rda")
# round data for rChart tooltip display
df$value <- round(df$value, 2)
n <- nPlot(value ~ Year, group = 'variable', data = df, type = 'lineChart')
n$yAxis(axisLabel = 'Labor and capital income (% national income)')
n$chart(margin = list(left = 100)) # margin makes room for label
n$yAxis(tickFormat = "#! function(d) {return Math.round(d*100*100)/100 + '%'} !#")
n$xAxis(axisLabel = 'Year')
n$chart(useInteractiveGuideline=TRUE)
n$chart(color = colorPalette)
n$addParams(height = 500, width = 800)
n$setTemplate(afterScript = '<style>
.nv-point {
stroke-opacity: 1!important;
stroke-width: 6px!important;
fill-opacity: 1!important;
}
</style>'
)
n$save('figures/Figure.html', standalone = TRUE)
```
The current version of nvd3 use path instead of circle to draw markers. Here is a piece of css code that i used to show markers.
#chart g.nv-scatter g.nv-series-0 path.nv-point
{
fill-opacity: 1;
stroke-opacity: 1;
}
And I also write something about this in https://github.com/novus/nvd3/issues/321, you could find that how i change the shape of makers.
I don't know how to change the size of markers. Trying to find a solution.
Selectively enable points to some series using the following logic in nvd3.
//i is the series number; starts with 0
var selector = 'g.nv-series-'+i+' circle';
d3.selectAll(selector).classed("hover",true);
However an additional parameter( like say 'enable_points':'true') in the data would make better sense. I will hopefully push some changes to nvd3 with this idea.
For current version of NVD3 (1.8.x), I use this D3-based solution (scripting only, no CSS file or style block required):
nv.addGraph(function() {
// ...
return chart;
},
function() {
// this function is called after the chart is added to document
d3.selectAll('#myChart .nv-lineChart .nv-point').style("stroke-width",
"7px").style("fill-opacity", ".95").style("stroke-opacity", ".95");
}
);
The styles used are exactly the styles added by NVD3 by applying the "hover" class to each point (when hovered). Adjust them to your needs.

How do I rotate a div with Raphael.js?

I am brand new to Raphael and am really stuck, I would like to rotate a div and its contents, using a button, with Raphael.
Ideally, I would like to have a smooth animation that goes from 0 degrees to -90 degrees when the button is clicked, then when the button is clicked again, the animation would reverse. I think I will change the id or class on mouse click so that I can use the same button for both animations. Would that be wise?
I really would like some help please, my Sandbox is at http://jsbin.com/isijo/ and you can edit it at http://jsbin.com/isijo/edit
Many thanks in advance for any help.
Hello and welcome to Raphael!
I have been looking at Raphael for more than a few months and although the documentation is not very comprehensive the software is brilliant.
I have been mixing Divs with Raphael objects in many ways and have got a "feel" for what works and what does not work.
I am recommending that you do not try rotating divs but (instead) Raphael objects.
First of all you could make a shiney set of Raphael buttons using this "tweakable" code below..
var bcontrols = new Array();
var yheight = 300;
for (var i = 0; i < 3; i++) {
bcontrols[i] = paper.circle(15 + (35 * i), yheight, 15).attr({
fill: "r(.5,.9)#39c-#036",
stroke: "none"
});
bcontrols[i].shine = paper.ellipse(15 + (35 * i), yheight, 14, 14).attr({
fill: "r(.5,.1)#ccc-#ccc",
stroke: "none",
opacity: 0
});
bcontrols[i].index = i;
bcontrols[i].shine.index = i;
bcontrols[i].shine.mouseover(function (e) {
this.insertBefore(bcontrols[this.index]);
});
bcontrols[i].mouseout(function () {
this.insertBefore(bcontrols[this.index].shine);
});
/* Called from Raphael buttons */
bcontrols[i].click(function () {
alert("Hello you just clicked " + this.index);
});
}
Next you need to know more about rotating Sets:
var s = paper.set();
s.push(paper.rect(10, 10, 30, 30, 10).attr({fill:'red'}));
s.push(paper.rect(50, 10, 30, 30, 5).attr({fill:'blue'}));
s.push(paper.rect(90, 10, 30, 30).attr({fill:'orange'}));
s.animate({rotation: "360 65 25"}, 2000);
This shows the degree of rotation and the centre of rotation of the "set" on the last line.
My additional Raphael resources website which aims to supplement documentation (Amongst other things):
http://www.irunmywebsite.com/raphael/raphaelsource.html
Heres where you can run the above 2 code examples without alteration:
http://raphaeljs.com/playground.html
I'm hoping this helped...
To my knowledge, there is no way to convert a div into a Raphael object. Since the Raphael rotate command is only defined for Raphael objects, your best bet is to create the major elements of your div (images, text, buttons and all) in Raphael instead of HTML, put them together in a single set, and, as the set is a Raphael object, rotate the set.
Consult Rotate a div in CSS and in IE filters. This is not the same as SVG, so if you need more layout magic, Raphael shapes are likely the way to go. You should be able to used JQuery in concert with Raphael to manipulate both in your window, but I am brand new to Raphael and have never done so.

Resources