Order bars in a barplot in r - bar-chart

I already have the script of my analysis and graphic, but what should I switch to change the order of the bars? Sorry for my bad English.
dados<- read.table("anova2.txt",h=T)
dados
attach(dados)
analise<- aov(dados$germ~dados$trat, data=dados)
summary(analise)
tapply(dados3$germ,dados3$trat, mean)
mean<- tapply(dados2$germ,dados2$trat, mean)
se<- tapply(dados$germ,dados$trat, function (x) sd(x/sqrt(length(x))))
grafico<-barplot(mean, beside=T, names.arg=c("C", "EM", "EQ", "CT","AG"),
xpd=F,ylim=c(0,100),
xlab="Tratamento", ylab="Taxa de Germinação (%)", cex.lab=1.3)
arrows(grafico, mean+se, grafico, mean, angle=90, code=1, length=0.1)
arrows(grafico, mean+se, grafico, mean-se, angle=90, code=3, length=0.1)

Related

X-scale does not update (sometimes) on signal change in a Vega chart

This is a somewhat simplified version of a chart I built recently. When I select the Extended time rage checkbox, more data points will show and the X axis will adjust accordingly.
When I clear the checkbox the additional data points will disappear (OK) but the X axis will not go back to the previous state (bug?).
Oddly enough if I change the time unit back and forth (for example monthly -> weekly -> monthly) then the X axis will eventually redraw correctly.
Why does this happen an how could I work-around the issue?
Also note that Y axis seem to update fine every time the checkbox toggles.
Chart renders with expected x-axis (when clicking checkbox) if xscale "domain" is changed from
"domain": {
"signal": "timeSequence(tbin_delivered.unit, tbin_delivered.start, tbin_delivered.stop)"
}
to
"domain": {"data": "deliveries", "field": "unit0", "sort": true}
Note: An issue with this workaround is that only time units with data are shown in the x-axis. For example, selecting time unit "daily" in the dropdown shows chart with no gaps for Saturday and Sunday when there were no deliveries.
Vega docs for ordinal scale and sort parameter:
https://vega.github.io/vega/docs/scales/#ordinal
https://vega.github.io/vega/docs/scales/#sort
View chart in Vega online editor
It looks like signal tbin_delivered is not updated when the time range shrinks. This is an edited chart; the only difference is in the tooltip (which will now show the value of tbin_delivered.start).
I wonder if this behavior is correct? tbin_delivered is calculated in the deliveries data stream, which is derived from stream fruit, which depends on the extendedtime signal, which does change.
Posting it as an answer because the link won't fit in a comment.
The issue appears to be the values of signal tbin_delivered.start and tbin_delivered.stop are not updated when dataset deliveries values are changed.
The workaround in this solution is to use Vega transform extent to obtain minimun and maximum values of the dataset after data have changed. The function timeSequence in xscale will then show the updated domain correctly.
Added Vega transform:
{
"type": "extent",
"field": "unit0",
"signal": "signal_delivered_extent"
}
Vega scale:
"scales": [
{
"name": "xscale",
"type": "band",
"range": "width",
"padding": 0.05,
"round": true,
"domain": {
"signal": "timeSequence(tbin_delivered.unit, signal_delivered_extent[0], signal_delivered_extent[1] + 1)"
}
Note that Vega expression function timeSequence: "Returns an array of Date instances from start (inclusive) to stop (exclusive)...". For the rendered x-axis domain to include the maximum value, the argument for stop in timeSequence function has to be higher than the maximum value in signal_delivered_extent.
View in Vega online editor

Editing CSV file in Emacs. Visualize first field with different color

I am trying to simplify the editing of a CSV file in Emacs. I would like to hightlight the first field of each row/line in different font foreground color. For example
KEYWORD1,description,value
KEYWORD2,description,value
KEYWORD3,description,value
KEYWORD4,description,value
I would like to highlight KEYWORD1, KEYWORD2, KEYWORD3, and KEYWORD4 in a different color. I tried to install csv-mode but it seems it does not offer this feature. I am using GNU Emacs 24.3.1 on Ubuntu 12.04.
Assuming csv-mode is a normal mode (I did not have it installed), this should work out of the box:
(add-hook 'csv-mode-hook
(lambda ()
(font-lock-add-keywords nil '(("^\\([^,]*\\)," 1 'font-lock-function-name-face)))))
Just replace font-lock-function-name-face with the face of your choice, if you don't like that particular color
I experimented a little bit with text properties, and came up with
(defun csv-highlight-1 ()
(interactive)
(save-excursion
(beginning-of-buffer)
(setq spos t)
(while spos
(setq spos (re-search-forward "^[^,]*," nil t))
(when spos
(let ((mod (buffer-modified-p)) (pos1 (line-beginning-position)) (pos2 (- spos 1)))
(put-text-property pos1 pos2 'font-lock-face '(:foreground "red"))
(put-text-property pos1 pos2 'front-sticky t)
(set-buffer-modified-p mod))))))
It seems to work, but I have to call it manually each time I update the buffer. But maybe that is ok.

GNUPLOT: How to use a function to decide the plot style

I have lots of series to draw in 1 plot. I want to decide the plot style/type according to the number of a series. Here is the example code of what I am aiming for:
title(i)=value(sprintf("title%i",i))
title1='x'
title2='x^2'
title3='x^3'
...
with(i)=value(sprintf("with%i",i))
with1='lines'
with2='points'
with3='boxes'
...
plot for [i=1:100] '-' title title(i) with with(i)
I have test the title() function works. But the with function does not work correctly.
Can you help me fix the code?
Or do you think there are other ways to achieve what I am aiming for?
It's possible to build a string of a plot command and then run this string:
p="plot x linewidth 1"
do for [i=1:10]{
p=p.sprintf(", x+%d linewidth %d", i, i+1)
}
print p
eval(p)
The output of the print command is:
plot x linewidth 1, x+1 linewidth 2, x+2 linewidth 3, ...
and this is the resulting plot:
Depending on what you finally want, this might be something for you:
do for [i=1:10]{
p=p.(i==1 ? "'myData.csv' with lines" : "")
p=p.(i==2 ? "'myData.csv' with steps" : "")
...
}
However, this looks pretty ugly.

Google-like plotting symbol?

I'm looking for some additional plot symbols. Here's my code as it stands:
library(maps)
map('state', 'north carolina')
x <- c(-81.18668,-78.38062)
y <- c(35.7767,35.7767)
points(x=x, y=y)
What I'm looking for are plot symbols similar to those used on Google Maps, preferably those used in directions maps (ie, point A and point B).
Are there any packages out there with these symbols built in, or does anyone have an idea for a quick hack? Thanks!
EDIT: Looking for plotting symbols like those showing the two points here:
http://goo.gl/maps/xjxqn
Basically, tear-drop shaped with labels (A and B).
Your question is kind of vague,
but here are some icons:
http://www.bestpsdfreebies.com/freebie/map-marker-icons/
Another library: http://abeliantechnologies.com/google_map_marker.php
Here is one way using the my.symbols function in the TeachingDemos package:
library(TeachingDemos)
ms.mappoint <- function(letter='', col='blue', txtcol='white', cex=1, ...) {
tmp <- seq( -3*pi/8, 11*pi/8, length.out=200 )
tmp.x <- cos(tmp)/3
tmp.y <- sin(tmp)/3 + 2/3
tmp.x <- c(tmp.x, 0, tmp.x[1])
tmp.y <- c(tmp.y, 0, tmp.y[1])
polygon(tmp.x, tmp.y, col=col)
text( 0, 2/3, letter, col=txtcol, cex=1, font=2 )
}
myx <- runif(10)
myy <- rnorm(10)
plot(myx,myy, ylim=c( min(myy)-.1, max(myy)+1) )
my.symbols(myx,myy, ms.mappoint, inches=1,
col=rainbow(10), letter=LETTERS[1:10], symb.plots=TRUE )
The overall shape could use some improvement, but that is just a matter of creating a matrix of x and y values to represent the shape.

Error generating localized variables (as constants)

The usage message for Set reminds us that multiple assignments can easily be made across two lists, without having to rip anything apart. For example:
Remove[x1, x2, y1, y2, z1, z2];
{x1, x2} = {a, b}
Performs the assignment and returns:
{a, b}
Thread, commonly used to generate lists of rules, can also be called explicitly to achieve the same outcome:
Thread[{y1, y2} = {a, b}]
Thread[{z1, z2} -> {a, b}]
Gives:
{a, b}
{z1 -> a, z2 -> b}
However, employing this approach to generate localized constants generates an error. Consider this trivial example function:
Remove[f];
f[x_] :=
With[{{x1, x2} = {a, b}},
x + x1 + x2
]
f[z]
Here the error message:
With::lvset: "Local variable specification {{x1,x2}={a,b}} contains
{x1,x2}={a,b}, which is an assignment to {x1,x2}; only assignments
to symbols are allowed."
The error message documentation (ref/message/With/lvw), says in the 'More Information' section that, "This message is generated when the first element in With is not a list of assignments to symbols." Given this explanation, I understand the mechanics of why my assignment failed. Nonetheless, I'm puzzled and wondering if this is necessary restriction by WRI, or a minor design oversight that should be reported.
So here's my question:
Can anyone shed some light on this behavior and/or offer a workaround? I experimented with trying to force Evaluation, without luck, and I'm not sure what else to try.
What you request is tricky. This is a job for macros, as already exposed by the others. I will explore a different possibility - to use the same symbols but put some wrappers around the code you want to write. The advantage of this technique is that the code is transformed "lexically" and at "compile-time", rather than at run-time (as in the other answers). This is generally both faster and easier to debug.
So, here is a function which would transform the With with your proposed syntax:
Clear[expandWith];
expandWith[heldCode_Hold] :=
Module[{with},
heldCode /. With -> with //. {
HoldPattern[with[{{} = {}, rest___}, body_]] :>
with[{rest}, body],
HoldPattern[
with[{
Set[{var_Symbol, otherVars___Symbol}, {val_, otherVals___}], rest___},
body_]] :>
with[{{otherVars} = {otherVals}, var = val, rest}, body]
} /. with -> With]
Note that this operates on held code. This has the advantage that we don't have to worry about possible evaluation o the code neither at the start nor when expandWith is finished. Here is how it works:
In[46]:= expandWith#Hold[With[{{x1,x2,x3}={a,b,c}},x+x1+x2+x3]]
Out[46]= Hold[With[{x3=c,x2=b,x1=a},x+x1+x2+x3]]
This is, however, not very convenient to use. Here is a convenience function to simplify this:
ew = Function[code, ReleaseHold#expandWith#Hold#code, HoldAll]
We can use it now as:
In[47]:= ew#With[{{x1,x2}={a,b}},x+x1+x2]
Out[47]= a+b+x
So, to make the expansion happen in the code, simply wrap ew around it. Here is your case for the function's definition:
Remove[f];
ew[f[x_] := With[{{x1, x2} = {a, b}}, x + x1 + x2]]
We now check and see that what we get is an expanded definition:
?f
Global`f
f[x_]:=With[{x2=b,x1=a},x+x1+x2]
The advantage of this approach is that you can wrap ew around an arbitrarily large chunk of your code. What happens is that first, expanded code is generated from it, as if you would write it yourself, and then that code gets executed. For the case of function's definitions, like f above, we cansay that the code generation happens at "compile-time", so you avoid any run-time overhead when usin the function later, which may be substantial if the function is called often.
Another advantage of this approach is its composability: you can come up with many syntax extensions, and for each of them write a function similar to ew. Then, provided that these custom code-transforming functions don't conlict with each other, you can simply compose (nest) them, to get a cumulative effect. In a sense, in this way you create a custom code generator which generates valid Mathematica code from some Mathematica expressions representing programs in your custom languuage, that you may create within Mathematica using these means.
EDIT
In writing expandWith, I used iterative rule application to avoid dealing with evaluation control, which can be a mess. However, for those interested, here is a version which does some explicit work with unevaluated pieces of code.
Clear[expandWithAlt];
expandWithAlt[heldCode_Hold] :=
Module[{myHold},
SetAttributes[myHold, HoldAll];
heldCode //. HoldPattern[With[{Set[{vars__}, {vals__}]}, body_]] :>
With[{eval =
(Thread[Unevaluated[Hold[vars] = Hold[vals]], Hold] /.
Hold[decl___] :> myHold[With[{decl}, body]])},
eval /; True] //. myHold[x_] :> x]
I find it considerably more complicated than the first one though.
The tricky issue is to keep the first argument of Set unevaluated.
Here is my suggestion (open to improvements of course):
SetAttributes[myWith, HoldAll];
myWith[{s : Set[a_List, b_List]}, body_] :=
ReleaseHold#
Hold[With][
Table[Hold[Set][Extract[Hold[s], {1, 1, i}, Hold],
Extract[Hold[s], {1, 2, i}]], {i, Length#b}], Hold#body]
x1 = 12;
Remove[f];
f[x_] := myWith[{{x1, x2} = {a, b}}, x + x1 + x2]
f[z]
results in
a+b+z
Inspired by halirutan below I think his solution, made slightly more safely, is equivalent to the above:
SetAttributes[myWith, HoldAll];
myWith[{Set[a : {__Symbol}, b_List]} /; Length[a] == Length[b],
body_] :=
ReleaseHold#
Hold[With][
Replace[Thread[Hold[a, b]], Hold[x_, y_] :> Hold[Set[x, y]], 1],
Hold#body]
The tutorial "LocalConstants" says
The way With[{x=Subscript[x, 0],...},body] works is to take body, and replace every
occurrence of x, etc. in it by Subscript[x, 0], etc. You can think of With as a
generalization of the /. operator, suitable for application to Mathematica code instead of
other expressions.
Referring to this explanation it seems obvious that something like
x + x1 + x2 /. {x1, x2} -> {a, b}
will not work as it might be expected in the With notation.
Let's assume you really want to hack around this. With[] has the attribute HoldAll, therefore everything you give as first parameter is not evaluated. To make such a vector-assignment work you would have to create
With[{x1=a, x2=b}, ...]
from the vector-notation. Unfortunately,
Thread[{a, b} = {1, 2}]
does not work because the argument to Thread is not held and the assignment is evaluated before Thread can do anything.
Lets fix this
SetAttributes[myThread, HoldFirst];
myThread[Set[a_, b_]] := mySet ### Transpose[{a, b}]
gives
In[31]:= myThread[{a, b, c} = {1, 2, 3}]
Out[31]= {mySet[a, 1], mySet[b, 2], mySet[c, 3]}
What looks promising at first, just moved the problem a bit away. To use this in With[] you have to replace at some point the mySet with the real Set. Exactly then, With[] does not see the list {a=1, b=2, c=3} but, since it has to be evaluated, the result of all assignments
In[32]:= With[
Evaluate[myThread[{a, b, c} = {1, 2, 3}] /. mySet :> Set], a + b + c]
During evaluation of In[32]:= With::lvw: Local
variable specification {1,2,3} contains 1, which is not an assignment to a symbol. >>
Out[32]= With[{1, 2, 3}, a + b + c]
There seems to be not easy way around this and there is a second question here: If there is a way around this restriction, is it as fast as With would be or do we lose the speed advantage compared to Module? And if speed is not so important, why not using Module or Block in the first place?
You could use Transpose to shorten Rolfs solution by 100 characters:
SetAttributes[myWith, HoldAll];
myWith[{Set[a_List, b_List]}, body_] :=
ReleaseHold[Hold[With][Hold[Set[#1, #2]] & ### Transpose[{a, b}],
Hold#body
]]
#Heike, yep the above breaks if either variable has already a value. What about this:
SetAttributes[myWith, HoldAll];
myWith[{Set[a_List, b_List]}, body_] :=
ReleaseHold#
Hold[With][Thread[Hold[a, b]] /. Hold[p__] :> Hold[Set[p]],
Hold#body]