How can I use bold and expression in ggplot with special characters? - r

I think that is very simple.
I'm using bold in the expression function in ggplot2.
It's all clear for me and it works.
But when I use it with special characters like mu*mol to have μmol or H[2]*O to have 2 as subscript, it doesn't work.
Practically it doesn't make bold the special characters.
I tried to use the bold function that I know with expression in ggplot.
I show you only the string of the plot code that I use to set label.
scale_y_continuous(sec.axis = sec_axis(trans = ~ ./5, name = expression(bold(atop(H[2]*O,(mu*mol~m^bold("-2")~s^bold("-1"))))),breaks=c(-3,-1.5,0,1.5,3)),breaks=seq(-10,20,10))
In the figure you can see that μ is not bold and the subscript 2 of H2O is not bold.

It's enough to use a single bold statement in your expression, but then you have to surround every subscript and superscript with quotation marks. This would still leave your greek letter mu without bold face, b/c plotmath doesn't have bold symbol fonts (see here). However, you can circumvent this by replacing mu with the unicode character (you can find them here).
Here I've just used the standard mtcars data set.
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = qsec)) +
geom_line() +
scale_y_continuous(sec.axis = sec_axis(trans = ~ ./5,
name = expression(bold(atop(H["2"]*O,("\u03bc"*mol~m^"-2"~s^"-1"))))))

Related

boldface of labels containing an expression with lower or equal symbol

I need to render in boldface the labels of the legend of a graph. One of the labels is an expression containing a "lower or equal" sign.
This is where I started from:
library(ggplot2)
df <- data.frame(x=factor(rep(0:1, 10)), y=rnorm(10), z=factor(rep(0:1, 10)))
ggplot(df, aes(x, y, shape=z)) +
geom_point() +
scale_shape_discrete(labels=c("Age > 65", expression(Age <= 65))) +
theme(legend.text=element_text(face="bold"))
In this way, the first label is bold, but the second is not. Following the suggestion here I tried to use plotmath bold():
library(ggplot2)
df <- data.frame(x=factor(rep(0:1, 10)), y=rnorm(10), z=factor(rep(0:1, 10)))
ggplot(aes(x, y, shape=z)) +
geom_point() +
scale_shape_discrete(labels=c("Age > 65", expression(bold(Age <= 65)))) +
theme(legend.text=element_text(face="bold"))
The label is rendered in bold only up to the "<=" sign. I have also tried to put the second part of the string within bold():
expression(bold(Age bold(<= 65)))
but to no avail. Any help is appreciated.
Tucked away in the plotmath documentation is the following:
Note that bold, italic and bolditalic do not apply to symbols, and hence not to the Greek symbols such as mu which are displayed in the symbol font. They also do not apply to numeric constants.
Instead, a suggested approach is to use unicode (assuming font and device support) which, in this case, means we can dispense with plotmath altogether.
ggplot(df, aes(x, y, shape=z)) +
geom_point() +
scale_shape_discrete(labels=c("Age > 65", "Age \U2264 65")) +
theme(legend.text=element_text(face="bold"))
While it is a little overkill for this particular issue, package ggtext makes complicated labels in ggplot2 a lot easier. It allows the use of Markdown and HTML syntax for text rendering.
Here's one way to write your legend text labels, using Markdown's ** for bolding and HTML's ≤ for the symbol.
library(ggtext)
ggplot(df, aes(x, y, shape=z)) +
geom_point() +
scale_shape_discrete(labels=c("**Age > 65**", "**Age ≤ 65**")) +
theme(legend.text=element_markdown())
(I'm on a Windows machine, and the default windows graphics device can have problems with adding extra spaces to symbols. Using ragg::agg_png() avoids the issue when saving plots, but also the next version of RStudio will allow you to change the graphics backend to bypass these problems.)

Irregular bolding in plotmath expression in ggplot2

I want to be able to pass an argument from a function into a label on a ggplot graph and for that label to be in bold. Unicode won't work because many unicode symbols don't render to pdf. Plotmath expressions can be split apart in paste(), which makes them ideal for this sort of work, however I can't work out how to get the Plotmath bold(x) expression to bold the entire compiled string.
For example, this code...
y <- 5
(g <- ggplot(data.frame(x = rnorm(100,0,1)), aes(x)) +
geom_histogram(bins = 100, fill = "skyblue") +
annotate("text", x = 1.5, y = 4, label = paste0("bold(x<=", y, "^{2})"), parse = T))
...yields...
As you can see the special character (less than or equal to) has come out fine. However the problem is that the x is bolded but not the rest of the string. How do I bold the entire string in a way that still allows me to pass the outside object y into the string?

math notation on ggplot2 axis labels

I want to add math notation to a ggplot2 axis using latex2exp, but I run into problems because scale_x_discrete() only accepts new label names when they are between quotation marks which renders the TeX() function, as used in the example below, as text. How can I both change the name of the labels while at the same time include math notation?
p<-ggplot(data=x, aes(x=y, y=x)) +
geom_errorbar(aes(ymin=x-ci, ymax=x+ci)) +
scale_x_discrete(breaks=c("label1","label2"),
labels=c("TeX('$\\alpha^\\beta$')","newlabel2"))
p
Checkout this vignette from the package creators:
https://cran.r-project.org/web/packages/latex2exp/vignettes/using-latex2exp.html
scale_color_discrete(labels=lapply(sprintf('$\\alpha = %d$', alpha), TeX))
For your code:
p<-ggplot(data=x, aes(x=y, y=x)) +
geom_errorbar(aes(ymin=x-ci, ymax=x+ci)) +
scale_x_discrete(breaks=c("label1","label2"),
labels = lapply(sprintf('$\\alpha^\\beta$'), TeX)
p
The other option, if your math notation is not very complicated, is to use bquote and UTF codes:
mn <- bquote("\u03B1 \u03B2")
labels=c(mn, "newlabel2")

R/ggplot2: use literal strings on parse()

Can part of the string I pass to parse(text=...) be taken as a literal string? Literal string means it will not try to interpret it.
For instance, I want to have the text "p-value" text in a plot (with the p italicized).
I am doing:
library(ggplot2)
ggplot(data.frame(x=rnorm(500)), aes(x)) + geom_histogram() + geom_text(label='italic(p)-value==0.10', parse=TRUE, x=-2, y=40)
Result:
The hyphen has a little too much padding and too big (because it takes it as the subtraction symbol), and it is not showing the number with the full precision I have used.
Can I just tell him to take part of that string as is?
How about this:
ggplot(data.frame(x=rnorm(500)), aes(x)) +
geom_histogram() +
annotate("text", label='italic(p)*"-value"=="0.15"', parse=TRUE, x=-2, y=40)
Here we use double quotes to specify character values and use * to place them right next to expressions.
Also note the change to annotate() rather than geom_text(). The latter would print out a 500 labels at the same location since it's tied to the data you specified in the ggplot call.
With set.seed(15), I get

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.

Resources