KarateSnowMachine
KarateSnowMachine

Reputation: 1510

Adding dynamic x and y title in ggplot2

I am working with a data set where I have a few variables that I'm constantly graphing that come out of CSV files with a specific naming convention. So for example I'll have something like:

p <- ggplot(plot_df, aes(x=ms, y=bandwidth)) + geom_line()

And by default, the graph's x and y titles will come out 'ms' and 'bandwidth', respectively. What I'd like to be able to do is to define a function that has a list of these mappings like:

"bandwidth"->"Bandwidth (GB/s)"
"ms"->"Time (ms)"

so I can feed p to a function that will essentially execute:

p + xlab("Time (ms)") + ylab("Bandwidth GB/s")

automatically without me having to keep specifying what the labels should be. In order to do this, I need to somehow get access to the x and y titles as a string. I'm having a hard time figuring out how I can get this information out of p.

EDIT: I guess typically the y axis comes out as 'value' because of melt, but for argument's sake, let's just say I'm doing the x axis for now.

Upvotes: 0

Views: 1870

Answers (1)

mnel
mnel

Reputation: 115485

They are stored in p$mapping (look at str(p))

Unless you want to do something really fancy with string manipulation, a look up table might be the best option for converting between variable names and correct labels

eg

d <- data.frame(x = 1:5, z = 12)

p <- ggplot(d, aes(x=x, y = z)) + geom_point()

labels.list <- list('x' = 'X (ms)', 'z' = 'Hello something')

p + xlab(labels.list[[as.character(p$mapping$x)]]) +   
    ylab(labels.list[[as.character(p$mapping$y)]])

enter image description here

You could write this into a function

label_nice <- function(ggplotobj, lookup) { 
   .stuff <- lapply(ggplotobj$mapping, as.character)
   nice <- setNames(lookup[unlist(.stuff)], names(.stuff))
   labs(nice)
}
# this will give you the same plot as above
p + label_nice(p, labels.list)

Upvotes: 6

Related Questions