daanoo
daanoo

Reputation: 781

Both custom tickmarks AND custom fontface in ggplot2

Apologies if this is straightforward or has already been answered, but I've searched high and low and haven't been able to find a solution anywhere.

I'm using ggplot2, trying to (1) specify custom tick marks to an axis which involve subscripts, and (2) trying to specify that some of these tick marks should be bold and others italic. I know how to do (1) and (2) separately, but when I try to do both together, only (1) succeeds.

y.labels<-c(expression(A[Subscript]),expression(B^Superscript))
y.face<-c("bold","italic")
testdf<-data.frame(x=rnorm(100),y=1:2)

Bold/italics don't appear when I supply custom labels:

ggplot(testdf,aes(x=x,y=y))+geom_point()+
  scale_y_discrete(label=y.labels)
  theme(axis.text.y=element_text(face=y.face)) 

But when I let the labels take their default values, bold/italics do appear:

ggplot(testdf,aes(x=x,y=y))+geom_point()+
 theme(axis.text.y=element_text(face=y.face)) 

As far as I can tell, the problem doesn't have anything to do with subscripting/superscripting, even though that is my aim, here (and which is why I'm passing the tick marks directly, rather than creating a factor variable with the desired labels, which does work). This doesn't work, either:

ggplot(testdf,aes(x=x,y=y))+geom_point()+
  scale_y_discrete(label=c("Custom1","Custom2"))+
  theme(axis.text.y=element_text(face=y.face)) 

If anyone can explain what's going on, here, and provide a solution whereby I can do both, I'd be much obliged. Thanks.

Upvotes: 0

Views: 81

Answers (1)

baptiste
baptiste

Reputation: 77116

plotmath doesn't honour fontface, you want to use bold() or italic() in your expressions,

y.labels<-c(expression(bold(A)[Subscript]),expression(italic(B)^Superscript))
ggplot(testdf,aes(x=x,y=y))+geom_point()+
    scale_y_discrete(label=y.labels)

Upvotes: 2

Related Questions