How to view a figure plotted by Plotly R from macOS Terminal

[2024-03-02 Sat] #permalink

This brief post provides a tip for macOS Terminal users on how to view a figure plotted by Plotly's R graphing library. Here is an example, adapted from Plotly's documentation:

suppressPackageStartupMessages(library(plotly))
fig <-  plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar') %>%
  layout(title = 'A Figure Displayed with print(fig)',
         plot_bgcolor='#e5ecf6', 
         xaxis = list( 
           zerolinecolor = '#ffff', 
           zerolinewidth = 2, 
           gridcolor = 'ffff'), 
         yaxis = list( 
           zerolinecolor = '#ffff', 
           zerolinewidth = 2, 
           gridcolor = 'ffff'))
print(fig)

Running the above R script on Terminal may end up with the following error message.

Error in viewer(index_html) : 
  'browser' must be a non-empty character string

It means that you need to provide a valid command to browse a local HTML file including the plotted figure to option browser.

A quick solution is to insert the following code before print() ing fig.

options(browser = "open")

Then, the default web brower of the user-wide setting will be launched to view the HTML file via the open(1) command.

If you do not want to repeat the above code every time, you can specify it in a configuration file that is loaded at R’s startup, such as ~/.Rprofile.


© 2006-2024 fixedpoint.jp