2

I have a large dataset for which I have multiple plots. I understand that using facets is recommended but my audience prefers multiple ranges in the same plot area. I have up to 7 different variables/ranges in the same plot - indicated by type in the below code snippet.

I have some parameters that remain unchanged for all plots (after the initial ggplot statement ggplot(dat, aes(x = loc_time, y = <variable_name>):

geom_point(aes(shape = type, color = type, fill = type)) + 
  scale_shape_manual(values = c(21,22,23,25,15,17,16)) + 
  scale_fill_manual(values = c('#e41a1c','#377eb8','#4daf4a','#984ea3', '#ff7f00','#a65628','#f781bf','black')) + 
  scale_color_manual(values = c('#e41a1c','#377eb8','#4daf4a','#984ea3', '#ff7f00','#a65628','#f781bf','black')) +
  scale_size_manual(values = c(1,2,2,1,2,2,1)) + 
  geom_line(aes(color = type))
  xlab("Local Time")

I could copy paste this info. to all plot statements but was wondering if there's a way to declare this just once.

I found this post Reset the graphical parameters back to default values without use of dev.off() but it doesn't quite answer my question.

Gautam
  • 2,597
  • 1
  • 28
  • 51
  • 4
    you could 1) use a function; 2) store the commands in a list; 3) create a "plot template" `p` and update it with new data `p %+% d` (this requires all data.frames to share the same names, i.e. long format) – baptiste Oct 23 '17 at 18:54
  • Can you give me an example of any of these approaches? I haven't done this before. Was trying to use `par()` but it just threw out errors - probably missing/wrong inputs from me. – Gautam Oct 23 '17 at 19:01
  • I'm plotting these values in a function as is and I don't want to use another function to achieve this. – Gautam Oct 23 '17 at 19:02

1 Answers1

4

You can do something like this:

Define your function:

format_cust <- function(.x) {
    .x + 
        geom_point(aes(shape = type, color = type, fill = type)) + 
        scale_shape_manual(values = c(21,22,23,25,15,17,16)) + 
        scale_fill_manual(values = c('#e41a1c','#377eb8','#4daf4a','#984ea3', '#ff7f00','#a65628','#f781bf','black')) + 
        scale_color_manual(values = c('#e41a1c','#377eb8','#4daf4a','#984ea3', '#ff7f00','#a65628','#f781bf','black')) +
        scale_size_manual(values = c(1,2,2,1,2,2,1)) + 
        geom_line(aes(color = type)) + 
        xlab("Local Time")
    }

Then apply it:

library(dplyr)
mtcars %>% 
    mutate(type = factor(carb)) %>% 
    ggplot(aes(mpg, cyl)) %>% 
    format_cust()
Zafar
  • 1,897
  • 15
  • 33
  • because of your `geom_point` call, you must use a function. Otherwise you could just add. – Zafar Oct 24 '17 at 13:59