Question

I refer to my previous question, and want to know more about characteristics of factor in R.

Let say I have a dataset like this:

temp <- data.frame(x=letters[1:5],
                   y=1:5)
plot(temp)

I can change the label of x easily to another character:

levels(temp[,"x"]) <- letters[6:10]

But if I want to change it into some expression

levels(temp[,"x"]) <- c(expression(x>=1),
                        expression(x>=2),
                        expression(x>=3),
                        expression(x>=4),
                        expression(x>=5))

The >= sign will not change accordingly in the plot. And I found that class(levels(temp[,"x"])) is character, but expression(x>=1) is not.

If I want to add some mathematical annotation as factor, what can I do?

Was it helpful?

Solution

I do not see any levels arguments in ggplot and assigning levels to a character vector should not work. If you are trying to assign expression vectors you should just use one expression call and separate the arguments by commas and you should use the labels argument in a scale function:

 p <- qplot(1:10, 10:1)+ scale_y_continuous( breaks= 1:10, 
                            labels=expression( x>= 1, x>=2, x>=3, x>= 4,x>=5,
                                              x>= 6, x>=7, x>= 8,x>=9, x>= 10) )
 p

enter image description here

OTHER TIPS

I would just leave them as character strings

levels(temp[,"x"]) <- paste("x>=", 1:5, sep="")

If you then want to include them as axis labels, you could do something like the following to convert them to expressions:

lev.as.expr <- parse(text=levels(temp[,"x"]))

For your plot, you could then do:

plot(temp, xaxt="n")
axis(side=1, at=1:5, labels=lev.as.expr)

Expression is used to generate text for plots and output but can't be the variable names per se. You'd have to use the axis() command to generate your own labels. Because it can evaluate expressions you could try...

plot(temp, xaxt = 'n')
s <- paste('x>', 1:5, sep = '=')
axis(1, 1:5, parse(text = s))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top