boldface of labels containing an expression with lower or equal symbol - r

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

Related

Plot title containing math $\\times$ sign

I would like to include the mathematical sign for a multiplication (like the lower-case x) in a plot title.
I have tried using latex2exp to no avail - can someone help me with this?
The reprex code is this:
library(ggplot2)
library(latex2exp)
ggplot(data = data.frame(number = round(rnorm(200, mean=55, sd=5))),
aes(x = number)) + geom_density() +
ggtitle(TeX("Title containing times sign here: $\\times$"))
And it produces this outcome:
I would like the square (indicating an unrecognized sign) to display as this sign: . It seems that other signs work (e.g. alpha) using this approach but I cannot figure out why the times sign poses an issue.
I'm not set on using latex2exp for the solution, as long as it works with the latex font (LM Roman 10).
Thanks a lot in advance.
It works for me with plotmath facilities: the %*% operator displays as the times symbol. For example,
library(ggplot2)
ggplot(data = data.frame(number = round(rnorm(200, mean=55, sd=5))),
aes(x = number)) + geom_density() +
ggtitle(expression("Title containing times sign here: " %*% ""))
Created on 2021-06-14 by the reprex package (v2.0.0)
I think that is what latex2exp was trying to do, so it might be that on your system the times symbol was missing, which is why you got the box. Funny that the Unicode solution worked.
One approach might be to use the unicode code for the multiplication symbol:
library(ggplot2)
ggplot(data = data.frame(number = round(rnorm(200, mean=55, sd=5))),
aes(x = number)) + geom_density() +
ggtitle("Title containing times sign here: \u00D7")
Unicode characters can be added to any string with \u and the 4 hex code. You can find the appropriate code from your OS or with Google.

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

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.

R - parse function doesn't work as expected

In the following example (please notice differences in y-axis labels) I use a variable to fill in an axis label in ggplot2. Interestingly ~ produces much larger spaces, and extra spaces show up around an enlarged -.
library(ggplot2)
#LabelY <- "Miles per Gallon-Car"
LabelY <- parse(text="Miles~per~Gallon-Car")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab(LabelY) + ylab(LabelY) +
theme(text=element_text(size=16))
print(a)
I am using parse because it allows me to use more complex examples including atop and greek letters.
Is there a way I can make use of parse to import complex strings while also preserving the desired "less spread out" appearance of the content?
It looks like enclosing the hyphenated term with backticks will allow you to keep the hyphen instead of turning it in a dash.
Here I put the new hyphenated version of the axis label on the x axis and leave the y axis as the original for comparison.
LabelY <- parse(text="Miles~per~Gallon-Car")
LabelY2 <- parse(text="Miles~per~`Gallon-Car`")
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab(parse(text = LabelY2)) + ylab(LabelY) +
theme(text=element_text(size=16))
As you pointed out in the comments, you can also use a curly bracket and single quote combination around the hyphenated term to get the same effect.
parse(text="Miles~per~{'Gallon-Car'}")

Resources