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

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.

Related

True negative sign in continuous y-axis scale

Owing to the journal's formatting requirement, I need to use a true negative sign (UTF-16: 2212) for my graphs. This is similar to this post, except that my existing plots are based on ggplot. Rather than reconfiguring them back to base R plot, I am hoping to find a ggplot2-native solution.
The current ggplot-based questions here unfortunately deal with text annotations, character axis ticks, or headings instead of continuous axis ticks. Meanwhile, the closest idea I have for the scale_y_continuous function is to use the label variable in the function or simply use break and manually tune all the relevant axes, but I am still figuring it out.
The manual way for now:
ggplot(test, aes(x = x, y = y)) +
geom_raster(aes(fill = value)) +
scale_x_continuous(breaks = -3:3, labels = c("\U2212\U0033","\U2212\U0032","\U2212\U0031",0,1,2,3))
This produces a plot with the default hyphen-minus sign on the y-axis and the true minus sign on the x-axis. However, the number has to be coded in UTF format, else it could be concatenated by the UTF reader into another UTF character (i.e. "\U22123" is a Chinese character instead of -3.)
May I ask if there is a more elegant and/or dynamic solution to this?
You can write your own labeller function.
library(ggplot2)
label_trueminus <- function(x){
ifelse(sign(x) == -1, paste0("\u2212", abs(x)), x)
}
ggplot(mtcars, aes(mpg-20, disp)) +
geom_point() +
scale_x_continuous(labels = label_trueminus)
Created on 2022-01-25 by the reprex package (v2.0.1)
or even shorter:
library(tidyverse)
label_parse <- function(breaks) {
parse(text = breaks)
}
# sample data
tibble(
a = -5:5,
b = rnorm(length(a))
) %>%
# sample plotting
ggplot(aes(a,b)) +
geom_point() +
# here's the magic
scale_x_continuous(labels = label_parse)

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

ggplot2: annotation with text, sub/superscript, and calculated values

I have searched here for a while and my question was partially answered by previous questions/answers. I am learning R, coming from Matlab. As the title says, I have a question about plot annotations. In Matlab it was fairly straightforward to have plot annotations that contained all sorts of data formats, and I am looking for something similar in R. I have already discovered paste and managed to put text and numbers into one annotation and I also figured out (to a degree...) what parse does, for example when displaying an r squared. My question is, how do I combine the two annotations in the code snippet into one annotation without R yelling at me? My solution with two annotations works for what I need, but I simply would like to know how to do it...
a <- 30 # some coefficients
b <- 70
r2 <- 0.87
anno1 <- paste("y = ",b,"ln(x) + ",a) # first annotation with a random equation
anno2 <- paste("r^2 == ", r2) # second annotation with a random r squared
Pdata <- data.frame("X" = 1:10, "Y" = 1:10) # some data
ggplot(Pdata,aes(x=Pdata$X,y=Pdata$Y)) +
geom_point() +
annotate("text", x=2, y=8, label=anno1, parse=FALSE) +
annotate("text", x=2, y=7, label=anno2, parse=TRUE)
Thanks y'all!
It took a while for me to figure this out (for my own projects), but here's a solution:
anno3 <- paste("'y ='~",b,"~'ln(x) +'~",a,"~r^2==~", r2)
Add it to your plot using + annotate("text", x=2, y=6, label=anno3, parse=TRUE)
The single quote identifies text to not evaluate. Combined, the pasted result should be written like an expression.
Here is one way to do the requested operation by using bquote
ggplot() +
geom_point(aes(x = 1:4, y = 1:4)) +
annotate("text", x=2, y=3,
label = deparse(bquote(~y ==~ .(b) ~ln(x)~ + .(a) ~r^2 ==~ .(r2))),
parse = T)
bquote quotes its argument except the terms wrapped in .() which are evaluated
annotate does not support expressions, one trick to get it to work is to deparse it and then parse it again

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.

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