Irregular bolding in plotmath expression in ggplot2 - r

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?

Related

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

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"))))))

add symbol to just one axis label in R [duplicate]

I have a plot which is generated thus:
ggplot(dt.2, aes(x=AgeGroup, y=Prevalence)) +
geom_errorbar(aes(ymin=lower, ymax=upper), colour="black", width=.2) +
geom_point(size=2, colour="Red")
I control the x axis labels like this:
scale_x_discrete(labels=c("0-29","30-49","50-64","65-79",">80","All")) +
This works but I need to change the ">80" label to "≥80".
However "≥80" is displayed as "=80".
How can I display the greater than or equal sign ?
An alternative to using expressions is Unicode characters, in this case Unicode Character 'GREATER-THAN OR EQUAL TO' (U+2265). Copying #mnel's example
.d <- data.frame(a = letters[1:6], y = 1:6)
ggplot(.d, aes(x=a,y=y)) + geom_point() +
scale_x_discrete(labels = c(letters[1:5], "\u2265 80"))
Unicode is a good alternative if you have trouble remembering the complicated expression syntax or if you need linebreaks, which expressions don't allow. As a downside, whether specific Unicode characters work at all depends on your graphics device and font of choice.
You can pass an expression (including phantom(...) to fake a leading >= within
the label argument to scale_x_discrete(...)
for example
.d <- data.frame(a = letters[1:6], y = 1:6)
ggplot(.d, aes(x=a,y=y)) + geom_point() +
scale_x_discrete(labels = c(letters[1:5], expression(phantom(x) >=80))
See ?plotmath for more details on creating mathematical expressions and
this related SO question and answer
plot(5, ylab=expression("T ">="5"))
You can use
expression("">=80)
So your full axis label like would look like:
scale_x_discrete(labels=c("0-29","30-49","50-64","65-79",expression("">=80),"All")) +
I have had trouble exporting plots when using unicode, but the expression function is more consistent.

"≥" or "≤" symbol in ggplot2 legend [duplicate]

I have a plot which is generated thus:
ggplot(dt.2, aes(x=AgeGroup, y=Prevalence)) +
geom_errorbar(aes(ymin=lower, ymax=upper), colour="black", width=.2) +
geom_point(size=2, colour="Red")
I control the x axis labels like this:
scale_x_discrete(labels=c("0-29","30-49","50-64","65-79",">80","All")) +
This works but I need to change the ">80" label to "≥80".
However "≥80" is displayed as "=80".
How can I display the greater than or equal sign ?
An alternative to using expressions is Unicode characters, in this case Unicode Character 'GREATER-THAN OR EQUAL TO' (U+2265). Copying #mnel's example
.d <- data.frame(a = letters[1:6], y = 1:6)
ggplot(.d, aes(x=a,y=y)) + geom_point() +
scale_x_discrete(labels = c(letters[1:5], "\u2265 80"))
Unicode is a good alternative if you have trouble remembering the complicated expression syntax or if you need linebreaks, which expressions don't allow. As a downside, whether specific Unicode characters work at all depends on your graphics device and font of choice.
You can pass an expression (including phantom(...) to fake a leading >= within
the label argument to scale_x_discrete(...)
for example
.d <- data.frame(a = letters[1:6], y = 1:6)
ggplot(.d, aes(x=a,y=y)) + geom_point() +
scale_x_discrete(labels = c(letters[1:5], expression(phantom(x) >=80))
See ?plotmath for more details on creating mathematical expressions and
this related SO question and answer
plot(5, ylab=expression("T ">="5"))
You can use
expression("">=80)
So your full axis label like would look like:
scale_x_discrete(labels=c("0-29","30-49","50-64","65-79",expression("">=80),"All")) +
I have had trouble exporting plots when using unicode, but the expression function is more consistent.

In ggplot2, can I split my titles into multiple lines automatically, instead of using the escape \n?

I've written a function to make graphs for a large dataset with hundreds of questions. All of the graphs are from the same dataset, and pull the title as a string from the 'graphtitle' column of a csv i've read in. Some of these titles are rather long and should be split to two lines. Perhaps because they're coming from the csv, the titles don't function with an \n escape, and even if they did, it seems like there should be an easier way than adding \n to each variable name in the appropriate place in the CSV.
Is there a way to make my function split the title lines automatically? I know I could change the size of the title, but that will render it largely illegible
MC.Graph <- function(variable){
p <- ggplot(data = newBEPS, aes_string(x=variable)) + geom_bar(aes(y = (..count..)/sum(..count..)), width = .5)+ scale_y_continuous(labels = percent)
p <- p + ggtitle(graphwords$graphtitle[graphwords$gw.varname == variable]) +
theme(plot.title = element_text(size =20, lineheight = .5, face = "bold"))
}
Here are two ways to break up a long string:
gsub('(.{1,10})(\\s|$)', '\\1\n', s) will break up string, s, into lines of length 10 separated by \n.
Use the strwrap function with a width argument wrapped with a paste function and collapse = \n argument.
Easier to understand with examples...
long_title <- "This is a title that is perhaps too long to display nicely"
gsub('(.{1,10})(\\s|$)', '\\1\n', long_title)
# [1] "This is a\ntitle that\nis perhaps\ntoo long\nto display\nnicely\n"
paste(strwrap(long_title, width = 10), collapse = "\n")
# [1] "This is a\ntitle\nthat is\nperhaps\ntoo long\nto\ndisplay\nnicely"
N.B. I believe strwrap is handled more gracefully (and guessing efficiently) in the stringi and/or stringr packages (see stringi::stri_wrap or stringr::str_wrap).

How to include a \perp symbol in a ggplot2 annotation?

I would like to put an annotation : E \perp c using ggplot2 annotate("text", label = ...).
I searched quite thorougly on the web but only managed to get a lone symbol using annotate("text", label = "symbol('\136')", parse = T).
Does anyone have a solution ?
Plotting code from help page:
p <- ggplot(df, aes(x = gp, y = y)) +
geom_point() +
geom_point(data = ds, aes(y = mean),
colour = 'red', size = 3)
p+geom_text( aes(x="b", y=-0.4, label = "E(y)*symbol('\\136')*b" ),
parse = TRUE)
After getting this to work I was also able to get annotate(text"...) working:
p+annotate("text", 1, -0.4, label="E(y)*symbol('\\136')*b", parse=TRUE)
The tricks: to mix your quoting characters which you did but to also use plotmath syntax which I'm guessing you might not have used.
Edit: * is not a quoting character. If anything, it should be called a linking character. In plotmath syntax every "atom" or function call needs to be separated from (or "linked-to" depending on how you view it) the adjoining atoms/functions. You can do this with * (the no-space separator/linker), ~ (the spacing separator/linker), or any of the dyadic operators in the plotmath vocabulary, examples including + , -, ==, !=.

Resources