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")`
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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With