Alex
Alex

Reputation: 2778

How to have a ggplot/plotly plot open in a browser from a shell script

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.

Upvotes: 0

Views: 503

Answers (1)

Alex
Alex

Reputation: 2778

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")

Upvotes: 0

Related Questions