Changing margin in a lapply call with prop.table and svytable - lapply

I am referring to this post. I have applied the proposed code to my data that has a similar structure, and it works well without the margin specification for prop.table:
lapply(names(dat)[1:9], function(x) prop.table(
svytable(bquote(~.(as.name(x)) + seg_2), dat_weight),
)*100)
However, when I add margin = 2 (as in the example), I get the following error:
Error in apply(x, margin, sum) : 'MARGIN' does not match dim(X)
I need the column wise proportions, but it gets messed up in the lapply call for a reason I don't know.

Related

Clicking on rowchart (dc.js) changes the percentage

I need to solve a problem with dc and crossfilter, I have two rowcharts in which I show the calculated percentage of each row as:
(d.value/ndx.groupAll().reduceCount().value()*100).toFixed(1)
When you click on a row in the first chart, the text changes to 100% and does not maintain the old percentage value, also the percentages of the rows of the same chart where the row was selected change.
Is it possible to keep the original percentage when I click ?, affecting the other graphics where it was not clicked.
regards
thank you very much
First off, you probably don't want to call ndx.groupAll() inside of the calculation for the percentages, since that will be called many times. This method creates a object which will get updated every time a filter changes.
Now, there are three ways to interpret your specific question. I think the first case is the most likely, but the other two are also legitimate, so I'll address all three.
Percentages affected by other charts
Clearly you don't want the percentage affected by filtering the current chart. You almost never want that. But it often makes sense to have the percentage label affected by filtering on other charts, so that all the bars in the row chart add up to 100%.
The subtle difference between dimension.groupAll() and crossfilter.groupAll() is that the former will not observe that dimensions filters, whereas the latter observes all filters. If we use the row chart dimension's groupAll it will observe the other filters but not filters on this chart:
var totalGroup = rowDim.groupAll().reduceCount();
rowChart.label(function(kv) {
return kv.key + ' (' + (kv.value/totalGroup.value()*100).toFixed(1) + '%)';
});
That's probably what you want, but reading your question literally suggests two other possible answers. So read on if that's not what you were looking for.
Percentages out of the constant total, but affected by other filters
Crossfilter doesn't have any particular way to calculate unfiltered totals, but if want to use the unfiltered total, we can capture the value before any filters are applied.
So:
var total = rowDim.groupAll().reduceCount().value;
rowChart.label(function(kv) {
return kv.key + ' (' + (kv.value/total*100).toFixed(1) + '%)';
});
In this case, the percentages will always show the portion out of the full, unfiltered, total denominator, but the numerators will reflect filters on other charts.
Percentages not affected by filtering at all
If you really want to just completely freeze the percentages and show unfiltered percentages, not affected by any filtering, we'll have to do a little extra work to capture those values.
(This is similar to what you need to do if you want to show a "shadow" of the unfiltered bars behind them.)
We'll copy all the group data into a map we can use to look up the values:
var rowUnfilteredAll = rowGroup.all().reduce(function(p, kv) {
p[kv.key] = kv.value;
return p;
}, {});
Now the label code is similar to before, but we lookup values instead of reading them from the bound data:
var total = rowDim.groupAll().reduceCount().value;
rowChart.label(function(kv) {
return kv.key + ' (' + (rowUnfilteredAll[kv.key]/total*100).toFixed(1) + '%)';
});
(There might be a simpler way to just freeze the labels, but this is what came to mind.)

dc.js line chart with range of colors

I have a composite graph of two line charts. For one of them i'm attempting to apply a custom color range based on the value of each point on the line:
.colors(['rgb(215,48,39)','rgb(244,109,67)','rgb(253,174,97)','rgb(254,224,144)'])
.colorDomain ([0,3])
.colorAccessor (d,i) ->
if d.points[i].data.value.avg > 50
return 0
else
return 3
The problem is I keep getting only one color for the entire graph... Not to mention d returns as an object of all the points instead of a single point... (maybe a hint of the problem?)
Am i doing something wrong here and/or is there an easier way to do this?
You didn't get an answer so I'll try to look into it with you.
First, I created a fiddle at http://jsfiddle.net/djmartin_umich/4ZwaG/.
.colors( ['rgb(215,48,39)', 'rgb(244,109,67)', 'rgb(253,174,97)', 'rgb(254,224,144)' ] )
.colorDomain ([0,3])
.colorAccessor(function(d, i){
if(d[i] && d[i].data.value > 150)
return 3;
else if(d.data.value > 150)
return 2;
else return 1;
});
I had to play around with the color accessor to get it to stop throwing errors. The method was called twice with an array of elements and twice for each element in the array (24 times total).
Once I got it compiling I inspected the chart and saw this:
The chart has a path element that defines the line and a bunch of circles that define the points on the line. The points are part of the tool-tip that display when you hover over the different points on the line.
The path seems to be colored by the value returned when the array of values was passed in and the hover-points on the line are each colored by the value returned for that element.
So the path of the line is given a single color. It sounds like your expectation is for different portions of the line to be colored differently based on their y-value, but this is not how the line is rendered.
The article at http://www.d3noob.org/2013/01/applying-colour-gradient-to-graph-line.html describes how you can use gradients to achieve the effect you desire. I believe the author is "hard-coding" the start and stop points for each gradient, so it won't get you all the way to your answer but it should help you get started.
I hope this helps!
-DJ

Change height of figures in GEF programmatically

I have a case where I have to add figures in another figure, i.e., nested figures.
My figure which will contain other figure extends org.eclipse.draw2d.Figure.
I want to change the height of this figure when it contains more than 4 figures, so that all the nested figures are visible at once.
So, in the paintFigure(Graphics graphics) method, I do this:
Rectangle r = getBounds();
if( getChildren().size() > 4 ) {
setBounds(new Rectangle(r.x, r.y, r.width, r.height + getChildren().size()-4)*10));
}
But this doesn't change the height. Well it does change it, for the time being, but when it is called again the next time, it again has the previous height, not the updated one.
Hence, visually the figure height doesn't change at all.
Any ideas on what am I doing wrong?
Or to do this in a different and/or better way?
I was updating the height in the paintFigure(), it was changing to previous height because it was taking values from the model. I changed the height in the model, and it worked fine.

changing d3.JSON in Hierarchical Bars to JSON.parse

I'm using http://bl.ocks.org/mbostock/1283663
and I'm trying to change the following code
d3.json("readme.json", function(root) {
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
});
to a JSON.parse (some data). I don't have a problem pulling the JSON data but I am totally confused about what is being setup in the rest of the d3.json process with the hierarchy.node(root), x.domain and down(root)
You're probably going to have to read a little more documentation before having a working understanding of what's going in this function. This is a tricky example to start with; I'm just going to walk you through what my process of trying to understand would look like. Going line by line:
d3.json("readme.json", function(root) {
This loads the referenced json file and calls function with it. 'root' starts out equal to the json file.
hierarchy.nodes(root);
Looking through the code, we find where hierarchy is declared:
var hierarchy = d3.layout.partition()
.value(function(d) { return d.size; });
So hierarchy is some kind of layout and hierarchy.nodes will add some useful attributes to root that will make it easier to graph.
x.domain([0, root.value]).nice();
searching for "x" in the example we find x = d3.scale.linear().range([0, w]). Tt appears that x is a linear scale. Basically, the x function will transform values in the domain - [0, root.value] to the range [0, w]. w is the width of the svg. root.value is a little trickier. The node page says
value - the node value, as returned by the value accessor
But what is the value accessor? The initial declaration of indicates it has something todo with root's 'size' attribute, but what? At this point, the documentation starts to get pretty confusing so you might want to pop open the debugger and see exactly what the value attribute of root and root's children looks like.
down(root, 0);
The down function is unique to the example and well commented. Try reading through it while referencing the documentation and see if you can figure it out.

How to get second attribute level with Selenium's xpath

I'm trying to check in Selenium if an element has a green border or not.
i can use //div[#id="target"]/#style to get the parsed style string applied... and use string search to search for the border... i have to work around some brosers showing the shorthand (border: solid 3px green) and other showing the expanded (border-style: solid; border-color: green....) ...but how could i do that more cleanly?
ideally something like: //div[#id="target"]/#style.borderColor
I also would like to avoid using the contains selector because the syntax is awful. But if it's the only way, so be it. of course.
XPath doesn't know anything about CSS styles, it doesn't understand the attributes and takes them just as simple strings. It would be weird if a XML query language understood CSS styles, right?
Besides, the getAttribute() uses a construct similar to XPath, but not XPath! It also selects the attribute via # sign, right. But consider this locator: "id=target#style". It would work, but it's definitely no XPath.
It would also return the explicitly set style attribute, not it's internal computed value, so it's useless unless there actually is a style attribute on the element. If there is style attribute defined, go for it.
Selenium itself can't give you the right answer (WebDriver has getCssValue(), but there's no counterpart for it in Selenium RC, afaik).
Therefore, the only way to get the computed style (the final value computed from all sources) of an element in Selenium RC is via JavaScript.
The script that has been working for me for ages (after a slight edit) is this (from quirksmode.org):
function getStyle(id, stylePropJs, stylePropCss) {
var x = document.getElementById(id);
if (x.currentStyle)
var y = x.currentStyle[stylePropJs];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(stylePropCss);
return y;
}
Note that IE needs a JavaScript name of the property, but every other browser uses CSS names. Also, you can't use the shorthand property and you definitely must use the expanded one. Therefore, in your case:
String script = "var x = document.getElementById('target');" +
"if (x.currentStyle) var y = x.currentStyle['borderTopColor'];" +
"else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(x,null).getPropertyValue('border-top-color');" +
"y;";
String color = selenium.getEval(script);
This returns the color of the top border (yep, you'll need to call it four times in order to get the whole border) of the target element. But guess what! Every browser returns the color in a different format. Fortunately, at least in Java, there's a Color class that can easily reformat it:
String color = Color.fromString(color).asHex();
Now that you have a hex encoded color stored, you can trivially make check whether it's green or not.

Resources