2

It is possible to run a r script from the terminal:

Let's say I have a file "message.r" which contains the following:

print("hello world")

I can run the script from the terminal with the the following command:

$ Rscript message.r
[1] "hello world"

Let's says now that I have a script containg code for a plot names plot.r with the following content:

x = c(1,2,3)
y = c(2,3,6)
plot(x,y)

Entering the command

Rscript plot.r

nothing happens

How to make display a plot from the terminal?

ecjb
  • 5,169
  • 12
  • 43
  • 79
  • See maybe: https://stackoverflow.com/questions/17748656/how-can-i-get-r-to-plot-something-in-unix-terminal. – TJ87 Sep 04 '19 at 15:25

2 Answers2

8

You need to set up a device driver. This saves the plot to the desktop.

x = c(1,2,3)
y = c(2,3,6)

pdf("~/Desktop/img.pdf")
plot(x,y)
dev.off()

system('open ~/Desktop/img.pdf')

Or directly onto the terminal window,

library(txtplot)
x = c(1,2,3)
y = c(2,3,6)

txtplot(x,y)

Sada93
  • 2,785
  • 1
  • 10
  • 21
  • Thank you @Sada93. Is there no way of displaying the plot without saving it or using an additional library? – ecjb Sep 04 '19 at 15:31
  • When executing a command from the terminal the plot will either need to be saved on disk or displayed in the terminal, what's the alternative option? You could open it once its saved but executing a system command `system('open ~/Desktop/img.pdf')` at the end of the script. – Sada93 Sep 04 '19 at 15:36
  • thanks again @Sada93. So there is no way like e.g. python to write the script of the plot in an editor like VIM, run it in the terminal, see the final result pop up AND ONLY THEN saving it if you want – ecjb Sep 04 '19 at 15:52
1

Consider launching an R session in terminal (which by default loads graphics and grDevices libraries and others including base, utils, stats etc.).

Then, source() your script which will run base plots and launch needed plot window to screen. At the end, quit session with q() as needed.

> R.exe
> source("myPlot.r")
> q()
Parfait
  • 104,375
  • 17
  • 94
  • 125
  • thanks for your comment @Parfait. As I just commented under the answer of Sada93, isn't there a way to write the script of the plot in an editor like VIM, run it in the terminal, see the final result pop up AND ONLY THEN saving it if you want? – ecjb Sep 04 '19 at 15:53
  • Do not compare different languages. There is no plotting module in Python's standard library and likely relies on third-party modules like `matplotlib` (much like above answer advises a different package). These other libraries likely initialize needed plotting interface in background and holds up terminal until plot window closes. Nevertheless, this R solution outputs a plot window to screen and allows you to save it to disk. – Parfait Sep 04 '19 at 15:58