Add greek letters to axis tick labels in R
Asked Answered
G

2

7

I have my axis ticks:

axis(4,at=c(1.6526,1.9720,2.6009,3.3403),las=1)

now I want to label them. The text should be something like this:

labels=c("alpha=0.1","alpha=0.05","alpha=0.01","alpha=.001")

But I want alpha to look like the greek character. Thanks!

Gourmont answered 25/10, 2012 at 12:7 Comment(3)
Possible duplicate: https://mcmap.net/q/274790/-adding-greek-character-to-axis-title/442852Wendelina
Well, I have more than one expression() so I was wondering how to do it.Gourmont
This is different to the duplicate question - the OP needs to combine a vector of expressions. That has been asked here before too, but I can;t find a good one to link to now.Tayib
U
8

You can use the expression without having to use paste

axis(4,at=c(0.75,1.75),labels=c(expression(alpha==0.1),expression(alpha==0.2)),las=1)
Unscratched answered 25/10, 2012 at 12:32 Comment(1)
You can do this automagically with some extra jiggery-pokery. See my Answer for one way.Tayib
T
5

Crafting these by hand is OK if there are a few labels, but is tedious and not-automated. There are ways to combine individual expression into an expression "vector", and we can automate the construction of the individual expressions. Here is one way, I forget if there are other ways or even if this is the canonical way (the general issue has been asked and answered on StackOverflow [including by me!] before but I couldn't find it in a very quick search).

op <- par(mar = c(5,4,4,6) + 0.1)
plot(1:10)
axis(1)
labs <- lapply(alpha, function(x) bquote(alpha == .(x)))
axis(4, at = seq(1, by = 2, length = 5),
     labels = do.call(expression, labs), las = 1)
par(op)

Which produces

enter image description here

I separated the the stages for exposition. The first is

> labs <- lapply(alpha, function(x) bquote(alpha == .(x)))
> labs
[[1]]
alpha == 0.1

[[2]]
alpha == 0.05

[[3]]
alpha == 0.01

[[4]]
alpha == 0.005

[[5]]
alpha == 0.001

which produces a list of calls.

The second step is to combine these into an expression, which I do with do.call()

> do.call(expression, labs)
expression(alpha == 0.1, alpha == 0.05, alpha == 0.01, alpha == 
    0.005, alpha == 0.001)

You can of course combine these:

labs <- do.call(expression, lapply(alpha, function(x) bquote(alpha == .(x))))
axis(4, at = seq(1, by = 2, length = 5),
     labels = labs, las = 1)
Tayib answered 25/10, 2012 at 12:46 Comment(1)
+1 The second figure coded up in example(plotmath) uses substitute() in a for loop for this (i.e. it uses an essentially identical strategy to yours).Andria

© 2022 - 2024 — McMap. All rights reserved.