Reputation: 145
I'm attempting to use a fractional value of pi in an annotation to a ggplot. The goal is to add a notation of the angle in both degrees and radians.
I've reviewed many other posts, but none concern the annotate() function with this particular set of requirements.
Thanks in advance for your answers.
This works:
library(ggplot2)
ggplot() +
geom_segment(aes(x = 0,
y = 0,
xend = 0.866,
yend = 0.5)
) +
annotate("text",
x = 0.3,
y = 0.25,
label = expression(30 * degree ~frac(pi,6)),
parse = TRUE)
I have tried a number of ways to add a multiplier for pi in the numerator, but various combinations of expression(), as.character(), concatenating the several parts with str_c() or paste().
Example:
library(ggplot2)
ggplot() +
geom_segment(aes(x = 0,
y = 0,
xend = 0.866,
yend = 0.5)
) +
annotate("text",
x = 0.3,
y = 0.25,
label = expression(30 * degree ~frac(11pi,6)),
parse = TRUE)
I was expecting the fraction to give me, well 11pi over 6 with pi appearing as the Greek letter and the numerator appearing over the denominator, not side-by-side as you would get typing into a text document (e.g., 11pi/6).
Upvotes: 1
Views: 281
Reputation: 813
If you're familiar with LaTeX, the latex2exp
package might help.
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2
library(latex2exp)
# define expression
exp_text <- r'($30 \degree$, $\frac{11 \pi}{6}$)'
# make plot
ggplot() +
geom_segment(
aes(
x = 0,
y = 0,
xend = 0.866,
yend = 0.5
)
) +
annotate(
geom = "text",
x = 0.3,
y = 0.25,
label = TeX(exp_text)
)
#> Warning in is.na(x): is.na() applied to non-(list or vector) of type
#> 'expression'
Created on 2023-10-11 with reprex v2.0.2
Upvotes: 1