In some cases of my Pie Chart, I would like to show the user the percentage relative to slices of the Pie Chart instead of showing the values of the slices.
For example: I have three slices in my pie: A representing 70% of the pie, B representing 15% of the pie and C representing 15% of the pie.
When I click to hide the slice A I want to show to the user the percentage of the remaining slices, in this example it'll be B = 50% and C = 50%.
Is it possible in NVD3?
Important: I don't want to reload the chart when click to hide some slice.
You can use chart.tooltipContent to override the chart tooltip label. The following is adapted from the live code example on NVD3's website. http://nvd3.org/livecode/#codemirrorNav
Example: http://plnkr.co/edit/UiGLIj?p=preview
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.showLabels(true);
chart.tooltipContent(function(key, x, obj){
var enabledTotal = data[0].values
.filter(function(item){return !item.disabled;})
.reduce(function(a, b){return a + b.value}, 0);
return Math.round((obj.value/enabledTotal) * 100) + "%";
})
d3.select("#chart svg")
.datum(data)
.transition().duration(1200)
.call(chart);
return chart;
});
Related
I want to achieve selection based on the bounding rectangle but with a different approach.
Scenario: If I draw object inside object, like first text, then rectangle over it, then ellipse and then triangle. Now I should be able to select the text or rectangle or ellipse OR the reverse order anyhow.
As I start hovering the triangle's bounding rect, the selection or active object should be triangle, but as I move my mouse over ellipse's bounding rect, the current object should be shown as ellipse and so on, irrespective of the order I have added the objects on canvas.
I tried with perPixelTargetFind and following solution Fabricjs - selection only via border, both the solutions are not working meeting my requirement.
I am using FabricJS version 3.6.3
Thanks in advance.
First you need to set perPixelTargetFind: true and targetFindTolerance:5.
Now you will face the issue for selection.
Issue: If you mousedown and drag on empty space, the object was getting selected.
Solution: Found a way to do that. I debugged through the fabric's mechanism to get objects on current mouse pointer location. There is a function _collectObjects which checks for intersectsWithRect (intersect with boundingRect points of the current object), isContainedWithinRect (do the points come inside the boundingRect), containsPoint(current mouse pointer points come in the current object location). So you need to override the _collectObjects function and remove containsPoint check. That will work.
Overridden function:
_collectObjects: function(e) {
var group = [],
currentObject,
x1 = this._groupSelector.ex,
y1 = this._groupSelector.ey,
x2 = x1 + this._groupSelector.left,
y2 = y1 + this._groupSelector.top,
selectionX1Y1 = new fabric.Point(min(x1, x2), min(y1, y2)),
selectionX2Y2 = new fabric.Point(max(x1, x2), max(y1, y2)),
allowIntersect = !this.selectionFullyContained,
isClick = x1 === x2 && y1 === y2;
// we iterate reverse order to collect top first in case of click.
for (var i = this._objects.length; i--; ) {
currentObject = this._objects[i];
if (!currentObject || !currentObject.selectable || !currentObject.visible) {
continue;
}
if ((allowIntersect && currentObject.intersectsWithRect(selectionX1Y1, selectionX2Y2)) ||
currentObject.isContainedWithinRect(selectionX1Y1, selectionX2Y2))
) {
group.push(currentObject);
// only add one object if it's a click
if (isClick) {
break;
}
}
}
if (group.length > 1) {
group = group.filter(function(object) {
return !object.onSelect({ e: e });
});
}
return group;
}
I'm plotting various weather data types, and am using Erik Flower's weather icons font set's wind arrow (.wi-wind, \u0b1) icon to represent wind direction. I'm trying, without success, to rotate them based on the direction. He as provided a style sheet that can handle the rotation, but I don't think that applies in highcharts.
Wind dir is a scatter plot being plotted on a single axis, with height of 0 so they all line up horizontally. When I apply rotation to the dataLabel symbols, via dataLabel.attr({ rotation: point.y }); in a $.each() loop, they rotate, but end up all wavy instead of along a horizontal line. I'm sure this is due to SVG rotation origin, but I cannot figure this one out. Any help?
-B-
--- EDIT ---
Here's a link to an image example of what's going on. Both rows are exhibiting the problem, both are using the same font/icon. The top is a second axis over the wind speed axis displaying dataLabels of a scatter plot that is then rotated based upon the direction (this one doesn't have the 180 deg adjustment applied). The lower are markers on a spline plot of wind speed that are rotated based upon the direction.
alignment probs with rotated wind symbols
The below snippet includes rotation/translation attempts for both sets of symbols. I only pulled the relevant lines. Wind speed is series 4, direction is 5.
// set wind speed data markers to symbols for direction, open circle with arrow point
//
// markers on spline
//
chart.get('windS').update({
marker: {
symbol: 'text:\uf0b1'
},
tooltip: {
pointFormatter: function() {
return '<span style="color:' + this.color +'">\u25CF</span> wind: <b>' + this.y + ' kts at ' +
chart.get('windD').yData[this.index] + '°</b><br/>';
}
}
});
// rotate the wind direction symbos to match the direction
$.each(chart.series[4].data, function(i, point) {
this.graphic
// .translate(-5, 5) // centers symbol on line
.attr({
// rotate symbol
// it's rotating at (0, 0) of the symbol's layout 20x36 rectangle
rotation: windIconDirection(chart.series[5].data[i].y),
// translateX: this.graphic.element.attributes.x,
// translateY: this.graphic.element.attributes.y
});
});
//
// data labels, not spline plot
//
// adjust position of wind speed symbols
// $.each(chart.series[4].data, function(i, point) {
// this.dataLabel.attr({
// translateY: -16
// })
// .css({
// });
// });
$.each(chart.series[5].data, function(i, point) {
this.dataLabel.attr({
rotation: point.y
});
});
I want to change the y axis max range based on plotting data. So When I draw the graph, it dynamically assign the y axis range based on maximum plotting data.
Currently, I am not defining any maximum range for Y axis in options to achieve the above. So it do dynamically assign maximum y-axis range, based on data plotting
This is my code for above implementation
var source = [];
var options = {
xaxis: {
...
}
yaxis: {
min: 0,
axisLabel: "Y",
axisLabelUseCanvas: false,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: "Verdana, Arial, Helvetica, Tahoma, sans-serif",
axisLabelPadding: 15
},
}
plotObj = $.plot($("#placeholder"), source, options) ;
It is working fine and allocating y axis max range dynamically. But, I have included "jquery.flot.selection.js" plugin to zoom the selected area. So it zoom to the ranges.yaxis.from to ranges.yaxis.to with below mentioned code
$("#placeholder").on("plotselected", function(ev, ranges) {
//clearInterval(protection_timer);
axes_data = plotObj.getAxes(); //get plotted axis ranges
axes_data.xaxis.options.min = ranges.xaxis.from ;
axes_data.xaxis.options.max = ranges.xaxis.to ;
axes_data.yaxis.options.min = ranges.yaxis.from;
axes_data.yaxis.options.max = ranges.yaxis.to;
...
plotObj.setData(graphData);
plotObj.setupGrid();
plotObj.draw();
});
Now, when user double click on the placeholder area, I need to reset beck the graph. But this time, as y axis max range is undefined, it is not resetting back. How can I get the y axis range, it was displaying in before zooming ? please give some suggestion
Expand your plotselected event with the second line here:
axes_data = plotObj.getAxes(); //get plotted axis ranges
axes_data.yaxis.originalMax = axes_data.yaxis.max; // save max value
axes_data.xaxis.options.min = ranges.xaxis.from;
and in the doubleclick event to reset the graph add the corresponding line:
axes_data.yaxis.max = axes_data.yaxis.originalMax; // restore max value
I created a Tree in D3.js based on Mike Bostock's Node-link Tree. The problem I have and that I also see in Mike's Tree is that the text label overlap/underlap the circle nodes when there isn't enough space rather than extend the links to leave some space.
As a new user I'm not allowed to upload images, so here is a link to Mike's Tree where you can see the labels of the preceding nodes overlapping the following nodes.
I tried various things to fix the problem by detecting the pixel length of the text with:
d3.select('.nodeText').node().getComputedTextLength();
However this only works after I rendered the page when I need the length of the longest text item before I render.
Getting the longest text item before I render with:
nodes = tree.nodes(root).reverse();
var longest = nodes.reduce(function (a, b) {
return a.label.length > b.label.length ? a : b;
});
node = vis.selectAll('g.node').data(nodes, function(d, i){
return d.id || (d.id = ++i);
});
nodes.forEach(function(d) {
d.y = (longest.label.length + 200);
});
only returns the string length, while using
d.y = (d.depth * 200);
makes every link a static length and doesn't resize as beautiful when new nodes get opened or closed.
Is there a way to avoid this overlapping? If so, what would be the best way to do this and to keep the dynamic structure of the tree?
There are 3 possible solutions that I can come up with but aren't that straightforward:
Detecting label length and using an ellipsis where it overruns child nodes. (which would make the labels less readable)
scaling the layout dynamically by detecting the label length and telling the links to adjust accordingly. (which would be best but seems really difficult
scale the svg element and use a scroll bar when the labels start to run over. (not sure this is possible as I have been working on the assumption that the SVG needs to have a set height and width).
So the following approach can give different levels of the layout different "heights". You have to take care that with a radial layout you risk not having enough spread for small circles to fan your text without overlaps, but let's ignore that for now.
The key is to realize that the tree layout simply maps things to an arbitrary space of width and height and that the diagonal projection maps width (x) to angle and height (y) to radius. Moreover the radius is a simple function of the depth of the tree.
So here is a way to reassign the depths based on the text lengths:
First of all, I use the following (jQuery) to compute maximum text sizes for:
var computeMaxTextSize = function(data, fontSize, fontName){
var maxH = 0, maxW = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none',
margin:0,
padding:0
});
$(div).css("font", fontSize + 'px '+fontName);
data.forEach(function(d) {
$(div).html(d);
maxH = Math.max(maxH, $(div).outerHeight());
maxW = Math.max(maxW, $(div).outerWidth());
});
$(div).remove();
return {maxH: maxH, maxW: maxW};
}
Now I will recursively build an array with an array of strings per level:
var allStrings = [[]];
var childStrings = function(level, n) {
var a = allStrings[level];
a.push(n.name);
if(n.children && n.children.length > 0) {
if(!allStrings[level+1]) {
allStrings[level+1] = [];
}
n.children.forEach(function(d) {
childStrings(level + 1, d);
});
}
};
childStrings(0, root);
And then compute the maximum text length per level.
var maxLevelSizes = [];
allStrings.forEach(function(d, i) {
maxLevelSizes.push(computeMaxTextSize(allStrings[i], '10', 'sans-serif'));
});
Then I compute the total text width for all the levels (adding spacing for the little circle icons and some padding to make it look nice). This will be the radius of the final layout. Note that I will use this same padding amount again later on.
var padding = 25; // Width of the blue circle plus some spacing
var totalRadius = d3.sum(maxLevelSizes, function(d) { return d.maxW + padding});
var diameter = totalRadius * 2; // was 960;
var tree = d3.layout.tree()
.size([360, totalRadius])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
Now we can call the layout as usual. There is one last piece: to figure out the radius for the different levels we will need a cumulative sum of the radii of the previous levels. Once we have that we simply assign the new radii to the computed nodes.
// Compute cummulative sums - these will be the ring radii
var newDepths = maxLevelSizes.reduce(function(prev, curr, index) {
prev.push(prev[index] + curr.maxW + padding);
return prev;
},[0]);
var nodes = tree.nodes(root);
// Assign new radius based on depth
nodes.forEach(function(d) {
d.y = newDepths[d.depth];
});
Eh voila! This is maybe not the cleanest solution, and perhaps does not address every concern, but it should get you started. Have fun!
I have a JavaFX 2 table that is displaying contact details for people, lets imagine there are three columns: first name, last name and email address. When my application starts it populates the table with several rows of data about the people already in the system.
The problem is that the column widths are all the same. Most of the time the first and last name is displayed in full but the email address is getting clipped. The user can double click the divider in the header to resize the column but that will become tedious quickly.
Once the table has been pre-populated I would like to programatically resize all the columns to display the data they contain but I can't figure out how to achieve this. I can see that I can call col.setPrefWidth(x) but that doesn't really help as I would have to guess the width.
If your total number of columns are pre-known. You can distribute the column widths among the tableview's width:
nameCol.prefWidthProperty().bind(personTable.widthProperty().divide(4)); // w * 1/4
surnameCol.prefWidthProperty().bind(personTable.widthProperty().divide(2)); // w * 1/2
emailCol.prefWidthProperty().bind(personTable.widthProperty().divide(4)); // w * 1/4
In this code, the width proportions of columns are kept in sync when the tableview is resized, so you don't need to do it manually. Also the surnameCol takes the half space of the tableview's width.
This works for me in JavaFX 8
table.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY );
col1.setMaxWidth( 1f * Integer.MAX_VALUE * 50 ); // 50% width
col2.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
col3.setMaxWidth( 1f * Integer.MAX_VALUE * 20 ); // 20% width
In the other examples you have the problem, the vertical scrollbar width is ignored.
As I use SceneBuider, I just define the MinWidth, and MaxWidth to some columns and to the main column I just define the PrefWidth to "USE_COMPUTED_SIZE"
After 3 years, finally I found the solution, javafx column in tableview auto fit size
import com.sun.javafx.scene.control.skin.TableViewSkin;
import javafx.scene.control.Skin;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class GUIUtils {
private static Method columnToFitMethod;
static {
try {
columnToFitMethod = TableViewSkin.class.getDeclaredMethod("resizeColumnToFitContent", TableColumn.class, int.class);
columnToFitMethod.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public static void autoFitTable(TableView tableView) {
tableView.getItems().addListener(new ListChangeListener<Object>() {
#Override
public void onChanged(Change<?> c) {
for (Object column : tableView.getColumns()) {
try {
columnToFitMethod.invoke(tableView.getSkin(), column, -1);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
});
}
}
If you had 4 columns and only last column needed to expand to fill the rest of the table width and the other columns remained the size I set in Scene Builder.
double width = col1.widthProperty().get();
width += col2.widthProperty().get();
width += col3.widthProperty().get();
col4.prefWidthProperty().bind(table.widthProperty().subtract(width));
Or if you had 2 columns that needed to expand then.
double width = col1.widthProperty().get();
width += col3.widthProperty().get();
col2.prefWidthProperty().bind(table.widthProperty().subtract(width).divide(2));
col4.prefWidthProperty().bind(table.widthProperty().subtract(width).divide(2));
Also, a very simple trick based on an AnchorPane will be a good solution.
We gonna wrap the TableView into a AnchorPane but also we gonna anchor the left and right side of the TableView like this:
AnchorPane wrapper = new AnchorPane();
AnchorPane.setRightAnchor(table, 10.0);
AnchorPane.setLeftAnchor(table, 10.0);
wrapper.getChildren().add(table);
This simple code will stretch the TableView in both directions (right and left) also, it will adjust whenever the scrollbar is added.
You can get an idea of how this works watching this animated gif.
Now you can resize the columns, adding these lines:
fnColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
lnColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 40 ); // 40% width
emColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
my idea.
table.getColumns().add(new TableColumn<>("Num") {
{
// 15%
prefWidthProperty().bind(table.widthProperty().multiply(0.15));
}
});
table.getColumns().add(new TableColumn<>("Filename") {{
// 20%
prefWidthProperty().bind(table.widthProperty().multiply(.2));
}});
table.getColumns().add(new TableColumn<>("Path") {{
// 50%
prefWidthProperty().bind(table.widthProperty().multiply(.5));
}});
table.getColumns().add(new TableColumn<>("Status") {
{
// 15%
prefWidthProperty().bind(table.widthProperty().multiply(.15));
}
});