0

I would like to make an R bash script that makes a ggplot/plotly plot when it runs

I have the following script which runs in interactive mode using littler.

#!/usr/bin/env r

library(plotly)
set.seed(955)
# Make some noisily increasing data
dat <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

p <- ggplot(dat, aes(x=xvar, y=yvar)) +
    geom_point(shape=1)      # Use hollow circles

p <- ggplotly(p)

message("before plot")
p
message("after plot")

After I make the file an executable (chmod +x) and run I do see the messages before plot and after plot, but no browser opens the plot.

How can I have a plot open from my script?

Context

It may seem odd that I am making a script to do plotting in bash. The reason I would like to do this is that I would eventually like to pass command line arguments to this script and have a plot pop up.

Alex
  • 2,603
  • 4
  • 40
  • 73
  • What file format do you want plotly to create (*eg*, png, svg?) If you're using straight-ggplot, maybe use `ggsave()` to create a png on the file system, then use `system()` to open the png? But I think any approach like this is brittle and not portable to other systems. Have you considered using knitr to create a html/pdf file? Or using just the preview pane in RStudio? – wibeasley Oct 28 '19 at 20:06
  • In the ideal situation I would like to have the plot open in a browser. – Alex Oct 28 '19 at 20:08
  • In that case, I suggest using [R Markdown](https://rmarkdown.rstudio.com/) to create an html file. The html file opens automatically in a browser if you use the 'ctrl+shift+k' shortcut in R Studio. – wibeasley Oct 28 '19 at 22:10

1 Answers1

0

This is not 100% want I was going for, but it seems to work okay. I am using the minimal cli application sxiv (any image viewer would work) to open the image after save. Below is the full script.

#!/usr/bin/env r

library(ggplot2)

base_dir <- getwd()
full_dif <- paste0(base_dir,"/p.jpg")

set.seed(955)
# Make some noisily increasing data
dat <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

p <- ggplot(dat, aes(x=xvar, y=yvar)) +
    geom_point(shape=1)      # Use hollow circles

ggsave(plot = p, filename = "p.jpg")

system_string <- paste0("/usr/bin/sxiv", " ", full_dif)

message("before plot")

system(system_string)

message("after plot")
Alex
  • 2,603
  • 4
  • 40
  • 73