6

I want to change axis labels dynamically using ggplot. The code below is a simple version of what I'd like to do. It correctly displays a degree symbol in the y axis.The commented out ylab lines of code are what I'd like to do but fail. I want to create the plotmath code, assign it to a variable (e.g. yLabel) and then have ggplot interpret it.

library(data.table)
library(ggplot2)

DT <- data.table(timeStamp=c(1:12), ColN1=runif(12, 0, 10))
DT.long <- data.table::melt(
  DT, id.vars = c("timeStamp"))

yLabel <- "Temperature~(~degree~F)"
yLabel1 <- expression("Temperature~(~degree~F)")

p <- ggplot(data = DT.long, aes(x = timeStamp, y = value)) + 
  xlab("Time") + 
  #    ylab( expression(paste("Value is ", yLabel,","))) +
#  ylab(yLabel) +
#  ylab(yLabel1) +
  ylab(Temperature~(~degree~F)) +

    scale_y_continuous() +
  theme_bw() +
  geom_line()
print(p)

2 Answers 2

3

Use bquote

Here is your dynamic component

temp <- 12

Assign it to the label using

ylab(bquote(Temperature ~is ~ .(temp) ~(degree~F)))

Or to address your additional question below

V = "Temperature is ("~degree~"F)"
W = "depth is ("~degree~"C)"

ggplot(data = DT.long, aes(x = timeStamp, y = value)) + 
  xlab("Time") +
  ylab(bquote(.(V)))

ggplot(data = DT.long, aes(x = timeStamp, y = value)) + 
  xlab("Time") +
  ylab(bquote(.(W)))
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't do the trick. I want to assign "Temperature is ..." to a variable (say V) and then use ylab(V). I tried ylab(bquote(.V). That didn't work.
oddly, if you want to set V conditionally, like: V = case_when(degree>90 ~ bquote("hot^{AF}"), ...) this won't work with case_when(), you need to use if statements like if (degree>90) V = bquote("hot^{AF}")
0

I had the same issue with dynamically modifying an axis label and B Williams answer helped me.

The solution:

dynamic <- "dynamic text"

# Put the dynamic text in its right context
str <- sprintf("Static label text [%s]", dynamic)

# Use multiplication "*" rather than "~" to build the expression to avoid unnecessary space 
complete_label <- bquote(.(str)[subscript]*"/L")

To verify that it works:

library(ggplot2)
ggplot() + labs(x = complete_label)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.