ggplot facet_grid label superscript - r

I am having trouble with putting subscript in facet_grid label. Here is
an example of the work I have been trying to do.
df <- data.frame(species=gl(2,10,labels=c('sp1','sp2')),
age=sample(3:12,40,replace=T),
variable=gl(2,20,labels=c('N1P1 var','N2P1 var')),
value=rnorm(40))
test.plot <- ggplot(data=df,aes(x=age,y=value)) +
geom_point() +
facet_grid(variable~species)
Now I want to make by vertical facet label as 'N[1]P[1] var' and so on,
where the numbers in the squared bracket means subscript.
I have consulted some helps in this platform regarding this, but none helped me. I have used expression, bquote as suggested, but nothing worked!

You need to do 2 things:
first, make your labels as plotmath expressions
variable_labels <-
c(expression(paste(N[1],P[1]~var)), expression(paste(N[2],P[1]~var)))
df <- data.frame(species=gl(2,10,labels=c('sp1','sp2')),
age=sample(3:12,40,replace=T),
variable=gl(2,20,labels=variable_labels),
value=rnorm(40))
And then change the default labeller function in facet_grid to "label_parsed"
test.plot <- ggplot(data=df,aes(x=age,y=value)) +
geom_point() +
facet_grid(variable~species, labeller = "label_parsed")

Related

ggplot2: How to use variables inside expression for labeling axis? [duplicate]

I'm writing a wrapper function around ggplot2 and having difficulty with one of the string arguments passed. Here's the sample code
myPlot <- function(tim, labx){
ggplot(subset(dat,TIME=tim), aes(x=WT, y=Var))+
geom_point(size=2)+
facet_wrap(~Dose)+
scale_x-continuous(expression(bold("Predicted"~labx~"Concentration ("*mu*"g/mL)")))
}
When I say myplot(100, "Week3"), my x-axis label is showing as "Predicted labx Concentration (µg/mL)" instead of "Predicted Week3 Concentration (µg/mL)". How do I fix this?
One solution is to use bquote() instead of expression(), and use .() inside of bquote to evaluate character (string) variables.
Below is a fully reproducible example of the issue.
library(ggplot2)
labx = "Week3"
p = ggplot(data.frame(x=1:5, y=1:5), aes(x, y)) +
geom_point() +
xlab(bquote(bold(Predicted~.(labx)~Concentration~(mu*g/mL))))
p

ordering function seq() in R with the order of input value

My apologize for my bad english i'm a student from france.
I have a little problem with a function in R, indeed i have a dataframe like that :
https://imgur.com/G5ToQrL
With this code :
testtransect2$TOTAL<-testtransect2$TOTAL*-1
plot(testtransect2$DECA,testtransect2$TOTAL,asp = 1)
xl <- seq(min(testtransect2$DECA),max(testtransect2$DECA), (max(testtransect2$DECA)-min(testtransect2$DECA))/1000)
lines(xl, predict(loess(testtransect2$TOTAL~testtransect2$DECA,span = 0.25), newdata=xl))
I want to create a plot with a smooth line which pass through all the point in the order of the dataframe but when i want put my line with my value xl and predict my plot is not like i want :
https://imgur.com/cSlhNtV
I link you a plot where you can see what i want :
https://imgur.com/mnVgvQ7
i think it's a problem of order in my xl value but i can't do it, if you have any solution
Thanks for give it to me
You can use ggplot
Storing your dataframe in df
df <- data.frame(DECA=c(0,10,15,-23,15,40,90,140,190,250,310,370,420),
TOTAL=c(0,-9,-15,-31.5,-48,-50,-44,-24,-17,-10,-6,-5,0))
You are interested in geom_point and geom_line. You can specify df$DECA and df$TOTAL in aes like this:
library(ggplot)
ggplot(df, aes(x=DECA, y=TOTAL)) +
geom_line() + geom_point()
Yielding
The "but when i want put my line with my value xl and predict my plot is not like i want" part is unfortunately unclear to me, please rephrase if this solution does not work for you.
Updated
There are other smooth_lines that may be added, eg. geom_smooth. Is this what you request?
ggplot(df, aes(x=DECA, y=TOTAL)) +
geom_line() + geom_point() +
geom_smooth(se=F, method = lm, col="red") + #linear method
geom_smooth(se=F, col="green") # loess method

Expression of italics and superscripts in ggplot axis title

I am sorry to ask this, but I can't seem to get this expression right to include in the ylab() or xlab() arguments of a ggplot2-object. It needs to read:
"2q (rarefied)". The "2" needs to superscripted, though.
I have fiddled with expression() and paste(), but it seems impossible. Any help is much appreciated.
edit: Some example:
dat<-as.data.frame(matrix(runif(100), 10,10))
names(dat) <- LETTERS[1:10]
library(ggplot2)
ggplot(dat, aes(A,B)) +
geom_point()+
xlab("some title")
All necessary information can be found in help("plotmath").
ggplot(dat, aes(A,B)) +
geom_point()+
xlab(expression({}^2*italic(q)~textstyle(group("(", rarefied, ")"))))

Adding bar labels with italics and superscript to a barplot

I am using barplot for my data.
I need to insert x-axis bar labels (sample names) which have superscripts and should be italicized. For instance, one of the sample names (bar labels) is lab(delta21). Apart from the whole name to be in italics, I want the delta in (delta21) to be in symbol form and (delta21) to be a superscript of lab. (This is nothing fancy, just how biological gene mutant names are written).
I have tried fiddling around with names.arg=expression() but could not get it to work.
Any suggestions/ideas are most welcome.
Please try this minimal example:
x <- rnorm(2)
barplot(x, names.arg = c(expression(paste(italic("1")^"st")), expression(paste(italic("2")^"nd"))))
italic() does the italic part, ^ does the superscript part.
You may need to use ggplot2 to create your barplot because "bold, italic and bolditalic do not apply to symbols, and hence not to the Greek symbols such as mu" quoted from this help page. I am also assuming that different numbers are assigned to different samples (e.g., Lab_delta21, Lab_delta22, etc).
library(ggplot2)
library(reshape)
## make up data
data_table <- cast(mtcars, gear ~., value="mpg", mean)
data_table <- rename(data_table, c("(all)"="mean_mpg"))
lab_number <- 21:23
fancy_labels <- sapply(lab_number, function(x) paste0("italic(Lab[delta]", "[", x, "])"))
ggplot(data_table, aes(gear, mean_mpg)) + geom_bar(stat = "identity") +
scale_y_continuous(limits=c(0, 30))+
geom_text(aes(label=fancy_labels), parse=TRUE, hjust=0.5, vjust=-0.5, size=7)
The second "[]" is necessary as in [delta][21] because without it geom_text recognize [delta21] as one word, without rendering delta into a Greek letter.

How to add vertical lines to ggplot boxplots in R

I am plotting boxplots from this data:
MY_LABEL MY_REAL MY_CATEGORY
1 [POS] .56 POS
1 [POS] .57 POS
1 [POS] .37 POS
2 [POS] .51 POS
1 [sim v] .65 sim v
...
I'm using ggplot2:
ggplot( data=myDF, aes( x=MY_LABEL, y=MY_REAL, fill=MY_CATEGORY ) ) +
scale_colour_manual( values=palette ) +
coord_flip() +
geom_boxplot( outlier.size = 0 )
This works fine, and groups the boxplots by the field MY_CATEGORY:
I'd like to do 2 things:
1) To improve the clarity of this plot, I'd like to add separators between the various blocks, i.e. between POS and sim v, between sim v and C, etc (see the ugly red lines in the plot).
I've been struggling with geom_vline with no luck.
Alternatively, I'd like to add blank space between the blocks.
2) If I print this plot in grayscale, I can't distinguish the different blocks. I'm trying to force a different palette with:
scale_colour_manual( values=c("black","darkgray","gray","white") )
Again, no luck, the plot doesn't change at all.
What would you suggest to do?
Would this work for you?
require(ggplot2)
mtcars$cyl2<- ifelse(mtcars$cyl > 4, c('A'), c('B'))
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot() + facet_grid(. ~ cyl2, scales = "free", space = "free")
would give something like this,
No one covered the horizontal line route, so I thought I'd add it. Not sure why geom_vline() wasn't working for you. Here's what I did (chose to play off of Eric Fail's approach):
require(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p <- p + geom_boxplot(aes(fill=factor(cyl))) + coord_flip()
p <- p + geom_vline(xintercept=c(1.5,2.5))
p
There's only three boxplots here, but in playing around, ggplot appears to place them at integer locations. Just figure out which box you want a line after (nth) and put the xintercept argument at n+0.5 for the line. You can obviously change the thickness and color to your liking: just add a size=width and colour="name" after the xintercept bit.
By the way, geom_vline() seems to work for me regardless of whether it's before or after coord_flip(). I find that counter-intuitive.
I'm not sure bdemarest is correct that you need the names to match the category names. I think the issue is that you used scale_colour_manual(), which applies if you used aes(..., colour=var) whereas you used fill=var. Thus, you need scale_fill_manual. Building on the above, we can add:
p <- p + scale_fill_manual(values=c("black","gray","white"))
p
Note that I've not defined any factor names for the colors to match. I think the colors are simply applied to your factor levels according to their order, but I could be wrong.
The end result of all of the above:
To change the fill colors, you need a named vector of values. The names need exactly match the y-axis category names.
scale_fill_manual(values=c("POS"="black", "sim v"="gray50",
"C"="gray80", "sim t"="white"))
To separate the y-axis categories, try facet_grid().
facet_grid(factor(MY_CATEGORY) ~ ., drop=TRUE)
I'm not sure that this will work because I don't have your data to test it.

Resources