Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically formatting individual axis labels in ggplot2

Tags:

r

ggplot2

This may end up being an expression or call question, but I am trying to conditionally format individual axis labels.

In the following example, I'd like to selectively bold one of the axis labels:

library(ggplot2)

data <- data.frame(labs = c("Oranges", "Apples", "Cucumbers"), counts = c(5, 10, 12))

ggplot(data = data) + 
  geom_bar(aes(x = labs, y = counts), stat="identity")`

No Bolding

There is similar problem here, but the solution involves theme and element_text. I am trying to use axis labels directly.

I can do this manually as below:

breaks <- levels(data$labs)
labels <- breaks
labels[2] <- expression(bold("Cucumbers"))

ggplot(data = data) + 
  geom_bar(aes(x = labs, y = counts), stat="identity") + 
  scale_x_discrete(label = labels, breaks = breaks)

Bolded

But, if I try to do it by indexing instead of typing out "Cucumbers", I get the following error:

breaks <- levels(data$labs)
labels <- breaks
labels[2] <- expression(bold(labels[2]))

ggplot(data = data) + 
  geom_bar(aes(x = labs, y = counts), stat="identity") + 
  scale_x_discrete(label = labels, breaks = breaks)

Which makes sense, because it is not evaluating the labels[2]. But, does anyone know how to force it to do that? Thanks.

like image 671
Sealander Avatar asked May 04 '15 17:05

Sealander


1 Answers

How about

breaks <- levels(data$labs)
labels <- as.expression(breaks)
labels[[2]] <- bquote(bold(.(labels[[2]])))

ggplot(data = data) + 
  geom_bar(aes(x = labs, y = counts), stat="identity") + 
  scale_x_discrete(label = labels, breaks = breaks)

Here we are more explicit about the conversion to expression and we use bquote() to insert the value of the label into the expression itself.

like image 68
MrFlick Avatar answered Oct 08 '22 11:10

MrFlick