17

I have a ggplot and I want to highlight only some specific x-axis labels according to a predefined condition.

I know that axis text is controlled by

theme(axis.text = element_text(...))

but this applies to all labels of the axis. What I want is that the formatting change be applied only the labels that have condition = 1.

PaoloCrosetto
  • 600
  • 1
  • 7
  • 16

1 Answers1

29

You can include for example ifelse() function inside element_text() to have different labels.

ggplot(iris,aes(Species,Petal.Length))+geom_boxplot()+
  theme(axis.text.x=
          element_text(face=ifelse(levels(iris$Species)=="setosa","bold","italic")))

Or you can provide vector of values inside element_text() the same length as number of levels.

ggplot(iris,aes(Species,Petal.Length))+geom_boxplot()+
 theme(axis.text.x = element_text(face=c("bold","italic","bold"),
                                   size=c(11,12,13)))

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • Thanks @Didzis-elferts. It works as advertised in your examples - and it makes a lot of sense too - but it does not work using my data. In particular, what happens is that the highlighted labels are the wrong ones. It is a strange behavior because the vector of conditions is correct. It must have something to do with sorting in ggplot. I'll try and work the solution out! – PaoloCrosetto Dec 16 '13 at 14:50
  • @PaoloCrosetto It is hard to comment why this solution doesn't work for you. If you updated your question with reproducible example, I could try to help. – Didzis Elferts Dec 16 '13 at 14:53
  • Thanks @Didzis. I am trying to do exactly this. The problem is that I cannot share my data (I have restrictive terms on their use) and i am not able to reproduce the problem with fake data... I'll do my best :) – PaoloCrosetto Dec 16 '13 at 14:57
  • 1
    solved. I had each level twice in the dataset (since I display two bars for each level) and hence the condition vector got recycled and it was hence not hitting in the right place. Duplicating the dataset and using the condition on the new dataset did the trick. Thanks for your answer! – PaoloCrosetto Dec 16 '13 at 15:36
  • Note that this solution won't work when faceting is done. For a solution you can go here - https://stackoverflow.com/q/45843759/2650427 – TrigonaMinima Feb 02 '18 at 19:29