0

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.

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, just what I was looking for. I had looked at str(p) before to try to see if I could find it, but I guess I missed it. Thanks.
I'm not sure how this function would be affected if you have a number of variables mapped to x or y (in separate layers).
I think the lookup table is enough for my purposes. Currently I've got it as a switch statement, but same idea. My plots aren't really that complex so that should work fine. I just get really sick of having to manually update labels when I change the output variable I'm displaying

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.