Git Product home page Git Product logo

irdisplay's Introduction

Native R kernel for Jupyter b-CI b-CRAN

For detailed requirements and install instructions see irkernel.github.io

Requirements

Installation

This package is available on CRAN:

install.packages('IRkernel')
IRkernel::installspec()  # to register the kernel in the current R installation
jupyter labextension install @techrah/text-shortcuts  # for RStudio’s shortcuts

Per default IRkernel::installspec() will install a kernel with the name “ir” and a display name of “R”. Multiple calls will overwrite the kernel with a kernel spec pointing to the last R interpreter you called that commands from. You can install kernels for multiple versions of R by supplying a name and displayname argument to the installspec() call (You still need to install these packages in all interpreters you want to run as a jupyter kernel!):

# in R 3.3
IRkernel::installspec(name = 'ir33', displayname = 'R 3.3')
# in R 3.2
IRkernel::installspec(name = 'ir32', displayname = 'R 3.2')

By default, it installs the kernel per-user. To install system-wide, use user = FALSE. To install in the sys.prefix of the currently detected jupyter command line utility, use sys_prefix = TRUE.

Now both R versions are available as an R kernel in the notebook.

If you encounter problems during installation

  1. Have a look at the full installation instructions!
  2. Search the existing open and closed issues.
  3. If you are sure that this is a new problem, file an issue.

Running the notebook

If you have Jupyter installed, you can create a notebook using IRkernel from the dropdown menu.

You can also start other interfaces with an R kernel:

# “ir” is the kernel name installed by the above `IRkernel::installspec()`
# change if you used a different name!
jupyter qtconsole --kernel=ir
jupyter console --kernel=ir

Run a stable release in a Docker container

Refer to the jupyter/docker-stacks r-notebook repository

If you have a Docker daemon running, e.g. reachable on localhost, start a container with:

docker run -d -p 8888:8888 jupyter/r-notebook

Open localhost:8888 in your browser. All notebooks from your session will be saved in the current directory.

On other platforms without docker, this can be started using docker-machine by replacing “localhost” with an IP from docker-machine ip <MACHINE>. With the deprecated boot2docker, this IP will be boot2docker ip.

Develop and run from source in a Docker container

make docker_dev_image #builds dev image and installs IRkernel dependencies from github
make docker_dev #mounts source, installs, and runs Jupyter notebook; docker_dev_image is a prerequisite
make docker_test #builds the package from source then runs the tests via R CMD check; docker_dev_image is a prerequisite

How does it know where to install?

The IRKernel does not have any Python dependencies whatsoever, and does not know anything about any other Jupyter/Python installations you may have. It only requires the jupyter command to be available on $PATH. To install the kernel, it prepares a kernelspec directory (containing kernel.json and so on), and passes it to the command line jupyter kernelspec install [options] prepared_kernel_dir/, where options such as --name, --user, --prefix, and --sys-prefix are given based on the options.

irdisplay's People

Contributors

flying-sheep avatar jankatins avatar michaelquinn32 avatar pwaltman avatar takluyver avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

irdisplay's Issues

Release on CRAN

IMO no issues are important enough to not release...

I've also added a small PR #21 to fix the one error, but after that (and installing base64enc from the git source... I do love the change in the compiler on win...) it's all good:

c:\data\external\R
λ build_rpackage.bat --Rdevel --check irdisplay
# Building packages: irdisplay
# Checking: yes
# Building for R-devel
c:\Program Files\R\R-devel
 - Building package irdisplay
* checking for file 'irdisplay/DESCRIPTION' ... OK
* preparing 'IRdisplay':
* checking DESCRIPTION meta-information ... OK
* checking for LF line-endings in source and make files
* checking for empty or unneeded directories
* building 'IRdisplay_0.3.0.9000.tar.gz'

# CHECKING the package
* using log directory 'c:/data/external/R/IRdisplay.Rcheck'
* using R Under development (unstable) (2016-04-25 r70548)
* using platform: x86_64-w64-mingw32 (64-bit)
* using session charset: ISO8859-1
* checking for file 'IRdisplay/DESCRIPTION' ... OK
* this is package 'IRdisplay' version '0.3.0.9000'
* checking package namespace information ... OK
* checking package dependencies ... OK
* checking if this is a source package ... OK
* checking if there is a namespace ... OK
* checking for executable files ... OK
* checking for hidden files and directories ... OK
* checking for portable file names ... OK
* checking whether package 'IRdisplay' can be installed ... OK
* checking installed package size ... OK
* checking package directory ... OK
* checking DESCRIPTION meta-information ... OK
* checking top-level files ... OK
* checking for left-over files ... OK
* checking index information ... OK
* checking package subdirectories ... OK
* checking R files for non-ASCII characters ... OK
* checking R files for syntax errors ... OK
* checking whether the package can be loaded ... OK
* checking whether the package can be loaded with stated dependencies ... OK
* checking whether the package can be unloaded cleanly ... OK
* checking whether the namespace can be loaded with stated dependencies ... OK
* checking whether the namespace can be unloaded cleanly ... OK
* checking loading without being on the library search path ... OK
* checking dependencies in R code ... OK
* checking S3 generic/method consistency ... OK
* checking replacement functions ... OK
* checking foreign function calls ... OK
* checking R code for possible problems ... OK
* checking Rd files ... OK
* checking Rd metadata ... OK
* checking Rd cross-references ... OK
* checking for missing documentation entries ... OK
* checking for code/documentation mismatches ... OK
* checking Rd \usage sections ... OK
* checking Rd contents ... OK
* checking for unstated dependencies in examples ... OK
* checking examples ... NONE
* checking PDF version of manual ... OK
* DONE

Status: OK

* installing to library 'C:/portabel/R/R/win-library/3.4'
* installing *source* package 'IRdisplay' ...
** R
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
*** arch - i386
*** arch - x64
* MD5 sums
packaged installation of 'IRdisplay' as IRdisplay_0.3.0.9000.zip
* DONE (IRdisplay)
c:\data\external\R

c:\data\external\R
λ

r CMD check

* building IRDisplay
[...]
* checking R code for possible problems ... NOTE
display_jpeg: no visible global function definition for 'namedlist'
display_png: no visible global function definition for 'namedlist'
[...]
* checking for code/documentation mismatches ... WARNING
Functions or methods with usage in documentation object 'display1' but not in code:
  display1

Codoc mismatches from documentation object 'display':
display
  Code: function(obj)
  Docs: function(data, metadata = NULL)
  Argument names in code not in docs:
    obj
  Argument names in docs not in code:
    data metadata
  Mismatches in argument names:
    Position: 1 Code: obj Docs: data

Codoc mismatches from documentation object 'display_html':
display_html
  Code: function(data = NULL, file = NULL)
  Docs: function(content)
  Argument names in code not in docs:
    data file
  Argument names in docs not in code:
    content
  Mismatches in argument names:
    Position: 1 Code: data Docs: content

Codoc mismatches from documentation object 'display_png':
display_png
  Code: function(data = NULL, file = NULL, width = NULL, height = NULL)
  Docs: function(data = NULL, filename = NULL, width = NULL, height =
                 NULL)
  Argument names in code not in docs:
    file
  Argument names in docs not in code:
    filename
  Mismatches in argument names:
    Position: 2 Code: file Docs: filename

* checking Rd \usage sections ... WARNING
Undocumented arguments in documentation object 'display_svg'
  'file'
Documented arguments not in \usage in documentation object 'display_svg':
  'filename'

Functions with \usage entries need to have the appropriate \alias
entries, and all their arguments documented.
The \usage entries must correspond to syntactically valid R code.
See chapter 'Writing R documentation files' in the 'Writing R
Extensions' manual.

using R v.3.5, IRdisplay throws unused argument error ("unused argument (size)")

This is similar to this recent question in this stackoverflow: https://stackoverflow.com/questions/50708887/display-html-report-in-jupyter-with-r

in my case, though, I'm trying to display a png file, and this is the error that I'm getting:
`Error in read(file, size): unused argument (size)
Traceback:

  1. IRdisplay::display_png(file = "/home/local/ARCS/pw2470/Pictures/Screenshot_from_2018-05-24_14-26-03.png")
  2. display_raw("image/png", TRUE, data, file, img_metadata(width,
    . height))
  3. prepare_content(isbinary, data, file)
  4. read_all(file, isbinary)
    `

The weird thing is that this used to work prior to me upgrading to R v.3.5 and re-installing/upgrading everything. is it a compatibility issue with R v.3.5.0 or is there a recent change that broke everything?

`display_jpeg` and `display_png`: display size does not change on jupyter lab

When I run the following code on Jupyter Notebook, the display size changes in accordance with the width option.

library(ggplot2)
g <- qplot(1:5, 1:5)
ggsave("foo.jpeg", g, width=2, height=1)
IRdisplay::display_jpeg(file="foo.jpeg", width=100)
IRdisplay::display_jpeg(file="foo.jpeg", width=300)

But when I run the same code on Jupyter Lab, the display size does not change.
Same behavior for display_png.
Is this a bug or is there any fix to this?

I am using IRkernel_1.0.2 and IRdisplay_0.7.0, and Python3.6 with jupyter 1.0.0 and jupytarlab 2.2.6 on a xubuntu 18.04 laptop.

On jupyter notebook:
nb

On jupyter lab:
lab

IRdisplay::html_display not showing any output

Hi, I am using IRdisplay in chrome on a jupyter notebook with conda, and it does not show any output or result in any error.
The lm* are linear regression models combined by stargazer. Stargazer returns a proper html file without any errors.

m <- capture.output(stargazer(lm_enroll,lm_grades,lm_score,
         digits = 3,
          header = FALSE,
          type = "html", 
          se = rob_se,
          title = "Linear Panel Regression Model",
          model.numbers = FALSE)

IRdisplay::display_html(paste("<center>","",m,"","</center>"))

install_github('irkernel/IRdisplay') redirects to hadley (doesn't exist)

I am unable to install IRdisplay, as it redirects (wrongly) to hadley.

> install_github('irkernel/IRdisplay')
Installing github repo(s) irkernel/IRdisplay/master from hadley
Downloading irkernel/IRdisplay.zip from https://github.com/hadley/irkernel/IRdisplay/archive/master.zip
Error in (function (url, name = NULL, subdir = NULL, config = list(),  :
  client error: (404) Not Found

Calling display_html from rpy2 produces flaky segfault error

I am get a segfault error when trying to call display_html from a python environment using rpy2 package. My R notebook is calling a simple a simple python script file that imports rpy2 then imports IRdisplay and then invokes display_html. This is obviously a proof of error script as my use case is calling display_html to render HTML output from a custom python application that I am trying to enable in R. Thanks for any help.

Given:

  • Create test_IRdisplay.py file with content:

from rpy2.robjects.packages import importr rdisplay = importr('IRdisplay') rdisplay.display_html('<h1>Hi</h1>')

  • R Packages installed are:
    IRkernel 1.2
    reticulate 1.22
    IRdisplay 1.0

  • Python Packages installed are:
    rpy2 = "3.4.5"
    notebook = "6.4.3"

Steps to Reproduce:

  1. Upload test_IRdisplay.py file to Jupyter
  2. Open new R notebook in Jupyter
  3. Type py_run_file("test_IRdisplay.py")
  4. Execute cell repeatedly until Dead Kernel error (for me the error always occurs on the 8th run - 7 successful runs, 8th is an error)

Logs show:
*** caught segfault *** address 0xb8, cause 'memory not mapped' An irrecoverable exception occurred. R is aborting now ...

I do see this warning after the firs time the cell is executed from step 4:
/usr/local/lib/python3.8/site-packages/rpy2/rinterface_lib/embedded.py:134: UserWarning: R was initialized outside of rpy2 (R_NilValue != NULL). Trying to use it nevertheless. warnings.warn(

Remove option jupyter.rich_display

This option belongs to the kernel and is only kept here to be compatible with an older IRkernel, which expects it set. Remove it after both projects have a release.

Adding metadata/styling from repr output

[edit]
Currently, without a change in the frontend, the best we can do is simple send the complete metadata to the frontend in the normal display data: If we manage the styling, we send the styling only once on the first exec of such code. But then the frontend (=Notebook) could reevaluate the cell which currently has the styling and we would no notice this and no send styling, and the notebook would end up without styling information.

See also jupyter/notebook#116 and jupyter/roadmap#9
[/]
It would be nice to be able to specify that something only needs to be displayed once, e.g. the styling for a table or an interactive plot.

The repr side probably only needs to document the way this should happen, the actually implementation needs to be in the display package.

From the old issue comment by @flying-sheep:


yeah, the point is that there needn’t be a new interface: we can simply add attributes to the character()/raw() returned, which avoids changing signatures.

an example where i loop a bunch of things, create their HTML reprs and only do setup once:

repr_html.stuff <- function(x, ...) {
    ...
    structure(html_markup, setup = list(stuff_setup_script = '<script>...</script>')
}

html_setups_seen <- character()
for (thing in things) {
    thing_repr <- repr_html(thing)
    thing_setups <- attr(thing_repr, 'setup')
    new_setups <- stuff_setups[intersect(html_setups_seen, names(thing_setups))]
    html_setups_seen <- c(html_setups_seen, names(new_setups))

    display_html_setups(new_setups)
    display_html(stuff_repr)
}

PS: for the implementation, we should have a list of seen setups, keyed by format and class. this way there will be less potential for name collisions. or we just us the passed code itself as key.

Lots of object do not display anything: in this case "formattable"

#devtools::install_github("renkun-ken/formattable")
library(formattable)

df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
    "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
  grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"),
  test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
  test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.2, 9.3, 9.1, 8.8),
  final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
  registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
  stringsAsFactors = FALSE)

f <- formattable(df, list(
  age = color_tile("white", "orange"),
  grade = formatter("span",
    style = x ~ ifelse(x == "A", style(color = "green", font.weight = "bold"), NA)),
  test1_score = normalize_bar("pink", 0.2),
  test2_score = normalize_bar("pink", 0.2),
  final_score = formatter("span",
    style = x ~ style(color = ifelse(rank(-x) <= 3, "green", "gray")),
    x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
  registered = formatter("span", 
    style = x ~ style(color = ifelse(x, "green", "red")),
    x ~ icontext(ifelse(x, "ok", "remove"), ifelse(x, "Yes", "No")))
))

f # does not display anything
class(f) # displays "formattable" "data.frame"
print(f) # nothing

I think this happens when print(f) does not print anything and we don't have anything to make a rich display...

In rstudio, the f already triggers something, so we really should implement the same way rstudio handles this...

x = print(f)

this also triggers a display in rstudio and sets x:

> x = print(f)
> class(x)
[1] "formattable_widget" "htmlwidget" 

So it seems we should implement a repr_html.htmlwidget (and maybe repr_html.formattable? I haven't fully understand the knit_print.*() hierarchy/call chain in formattable yet) and also check that we have the same display mechanism as rstudio (do they have a way to deliver plots to the plot area?).

Regarding things we have no rich printing for: I've no clue how to reliably tell if we miss a repr_xxx.class_type (and tell the user that they should bug us or the package owner for such a method) or that the package author didn't want a visible output. If someone has a clue...

CC: @renkun-ken (owner of the formattable package)

row & column sizes centered instead of left-justified

At least on Jupyter notebooks with irkernel 1.1 and irdisplay 0.7, printing a data.frame generated a table with the rows and columns listed in the upper left of the table (eg., A data.frame 14 x 60). For example:

Screen Shot 2021-01-12 at 13 55 13

However, in Jupyter lab 3.0.3, the row & column size information is centered in the top-middle of the table. For example:

Screen Shot 2021-01-12 at 13 56 06

...so for tables with many rows, the user must now constantly scroll over just to see the data.frame size. Is there a way to move the row & column size information back to the top left of the table?

add tests

currently only the options are tested, but there should be tests for each display_*. Probably easiest wit two helper functions:

last_data <- NULL
display_func <- function(data, metadata=NULL){
   last_data <<- list(data, metadata)
}
get_last_data <- function(){
    ret <- last_data
    last_data <<- NULL
    ret
}
options(jupyter.base_display_func=display_func)

# tests ala
display_html(...)
assert_equal(get_last_data(), list(...))

The output from IRdisplay is not so familiar with that from traditional console

Background

This is when I want to use a package called "table1", which outputs an HTML file with its own CSS-style and then automatically activate a page in the browser to show the output.

When I use the traditional console

image

All well when using the traditional console

When I use the JupyterLab without IRdisplay

image

It outputs some codes instead of a visualized table.

When I use the IRdisplay

image

It shows the table correctly but with the wrong style.

My problem

Umm... I want to know if there is any method for solving this issue? Because the style of the table is very important for an article that without it, I have to draw it by myself in the WORD.
Or is there any means for me to let the package to activate this own page like that it does in the traditional console?
Thank you very much~~~

Can I use display_javascript to replace magic

Hello, I wanted to remove autoscrolling in jupiterlab and while I get hundreds of hits in python it seems very complicated to find out how to do it in R.
From this post on SO it seems that I should be able to do
IRdisplay::display_javascript('IPython.OutputArea.auto_scroll_threshold = 99999;') however when I do this in jupyterlab I get the error :
Javascript Error: IPython is not defined
Note that this seems to be working in jupyter-notebook
Sorry for the trivial question but I am new to jupyter in R

Clear cell output programmatically

In IPython I call from IPython.display import clear_output to clear a cell output. How do I achieve the same with IRKernel or IRDisplay. I’m using reticulate to import a python module and call a user defined method which sends Brno back to the client updating its progress. Without clearing the output on each progress change, the results are displayed in succession.

display_jpeg(file=url(... invalid filename argument

Following the example in the manual:

> display_jpeg(file = url('http://example.com/example.jpg'), width = 100)

I did:

> display_jpeg(file=url('https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg'))
Error in file.info(file): invalid filename argument
Traceback:

1. display_jpeg(file = url("https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg"))
2. display_raw("image/jpeg", TRUE, data, file, img_metadata(width, 
 .     height))
3. prepare_content(isbinary, data, file)
4. file.info(file)

Just url:

> url('https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg')
A connection with                                                                        
description "https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg"
class       "url-libcurl"                                               
mode        "r"                                                         
text        "text"                                                      
opened      "closed"                                                    
can read    "yes"                                                       
can write   "no"                                                        

Verison info:

> sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.4 LTS

Matrix products: default
BLAS: /opt/conda/lib/R/lib/libRblas.so
LAPACK: /opt/conda/lib/R/lib/libRlapack.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] IRdisplay_0.4.4 bit64_0.9-5     bit_1.1-12     httr_1.3.1     

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.15      digest_0.6.15     crayon_1.3.4      R6_2.2.2         
 [5] repr_0.13         jsonlite_1.5      magrittr_1.5      evaluate_0.10.1  
 [9] stringi_1.1.7     curl_3.2          uuid_0.1-2        data.table_1.11.0
[13] IRkernel_0.8.11   tools_3.4.1       stringr_1.3.0     compiler_3.4.1   
[17] base64enc_0.1-3   htmltools_0.3.6   pbdZMQ_0.3-2      openssl_1.0.1    

Display HTML output

Hi, I just opened an issue on IRkernel, IRkernel/IRkernel#392 but I realized that perhaps it is related to IRdisplay and not the kernel itself. should I close the issue and move it here instead?

Final discussion about design

#5 totally derailed and IRkernel/IRkernel#97 makes this urgent so let me get this done:

We want the following functions:

  1. high level display creating a mimebundle by calling all repr_* functions on an object, then calling base_display on that mimebundle
  2. low level display_mimebundle and display1 functions directly accepting mimebundle-like lists
  3. high level display_* convenience functions for a single object or file.

more questions:

  1. should we call base_display only with base64 encoded text strings or also with raw vectors and rely on simplejson automatically base64’ing those?

  2. i like the ... API instead of a dedicated list: which should we do:

    • display_mimebundle(list('application/png' = bar,
                              'image/png' = foo),
                         metadata = list(
                              'image/png' = list(width = 400)))
    • display_mimebundle('application/png' = bar,
                         'image/png' = foo, 
                         metadata = list(
                               'image/png' = list(width = 400)))
    • display_mimebundle('application/png' = bar,
                         'image/png' = list(foo, width = 400))

    the latter of course would also accept a dedicated metadata parameter.


change in IRkernel: jupyter.result_mimetypesjupyter.display_mimetypes

…which we then use here in the new display function to determine which reprs to call

since IRkernel sets the option (if not also set) and this project doesn’t depend on IRkernel: should this project also set a default for that option?

IRdisplay::display_pdf not showing any output

I am trying to display pdf in the Google Colaboratory environment.

When I ran:

library(IRdisplay)
display_pdf(file='test.pdf')

The R notebook returned nothing.

I had correct pdf format file in the file system, and all other functions display_png, display_jpeg, display_svg worked for me.

Audio player

I'm wondering if there's a recognised way of displaying an audio media player as part of cell output in a Jupyter / IRkernel notebook?

What I'd like to be able to do is something like:

display('myFile.wav')
display('myMidi.mid')
display(myAudioObject)

There doesn't seem to be a display function for it - is the best route to try to wrap something as an HTMLwidget and then render that?

Error when running plot.ly commands

Hello!

I am trying to execute the following lines of codes (from here: https://plot.ly/ggplot2/), but then it yields an error message, saying: "HTML widgets cannot be represented in plain text (need html)". Why is this and how can this be fixed?

require(ggplot2); require(plotly)

set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]

p <- ggplot(data = d, aes(x = carat, y = price)) +
geom_point(aes(text = paste("Clarity:", clarity)), size = 4) +
geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)

(gg <- ggplotly(p))

Error: widget$status_code == 200 is not TRUE. Please Help!

This is my code in R

trend1 <- gtrends (c(paste0( "House for sale in London", "House for sale in Birmingham")), geo = "GB", time = "2004-01-01 2016-12-30")

And the error is

Error: widget$status_code == 200 is not TRUE

It doesn't seem to be a common error. I don't know what happens to it because I don't think the code is wrong though. Please help!

`options(c("repr.plot.width", "repr.plot.height"))` not handled as expected.

This StackOverflow question: https://stackoverflow.com/q/72698223 illustrates what looks like a bug in the display of graphics. This script:

temp <- mtcars[, 1:3]
colnames(temp) <- c("x1", "z", "y1")

plotting_function <- function(data_to_vis) {
  
  p1 <- ggplot(data_to_vis, aes(x=x1, y=y1)) +
    geom_point(size = 3)       
  options(repr.plot.width = 5, repr.plot.height = 5)     
  print(p1)
  p2 <- ggplot(data_to_vis, aes(x=x1, y=y1)) +
    geom_point() +
    facet_wrap(~z) +
    theme(aspect.ratio = 1)
  options(repr.plot.width = 20, repr.plot.height = 20) 
  print(p2)
}

library(ggplot2)
plotting_function(temp)

uses the 2nd options() setting to set the width and height of both plots. To get them to appear as intended, the first setting needs to be moved after the print(p1) statement.

This was tested on the R kernel at https://jupyter.org/try, which reports "The version of the notebook server is: 6.4.10", "Current kernel information: R version 4.1.2 (2021-11-01)".

more display_* functions

Compared to ipython, we are currently missing:

  • display_markdown -> that's interesting because pander, which displays mostly every thing in R in markdown
  • display_jpeg -> to complement the *_png and *_svg one?
  • display_latex -> also lots of stuff in R which can transform to a latex representation
  • display_json -> that's the one I want -> jupyter/jupyter_client#6 (comment) :-)
  • display_pdf -> nice for plotting, which should be included in latex/pdf
  • display_javascript -> in python used to implement magics, which influences the behaviour of the notebook... Not sure if we need that...

as.character(htmlwidget) gives error in the display system

#devtools::install_github("renkun-ken/formattable")
df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
    "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
  grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"),
  test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
  test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.2, 9.3, 9.1, 8.8),
  final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
  registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
  stringsAsFactors = FALSE)
library(formattable)

f <- formattable(df, list(
  age = color_tile("white", "orange"),
  grade = formatter("span",
    style = x ~ ifelse(x == "A", style(color = "green", font.weight = "bold"), NA)),
  test1_score = normalize_bar("pink", 0.2),
  test2_score = normalize_bar("pink", 0.2),
  final_score = formatter("span",
    style = x ~ style(color = ifelse(rank(-x) <= 3, "green", "gray")),
    x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
  registered = formatter("span", 
    style = x ~ style(color = ifelse(x, "green", "red")),
    x ~ icontext(ifelse(x, "ok", "remove"), ifelse(x, "Yes", "No")))
))
w <- as.htmlwidget(f)
h <- htmlwidgets:::toHTML(w, standalone = FALSE, knitrOptions = NULL)
as.character(h)

Results in

Error: is.vector(vec) || is.factor(vec) is not TRUE
Traceback:

1. tryCatch({
 .     for (mime in getOption("jupyter.display_mimetypes")) {
 .         r <- mime2repr[[mime]](obj)
 .         if (!is.null(r)) 
 .             data[[mime]] <- r
 .     }
 . }, error = handle_error)

"

SVG is sent despite options to not send it

I remove the svg display options like this:

old = getOption("jupyter.display_mimetypes")
options(jupyter.display_mimetypes = old[1:length(old)-1]) # the last element is svg
print(getOption("jupyter.display_mimetypes"))
[1] "text/plain"             "text/html"              "text/markdown"         
[4] "text/latex"             "application/json"       "application/javascript"
[7] "application/pdf"        "image/png"              "image/jpeg" 

But the notebook still contains svg and I can't right click on the image and save the image :-(

let `display()` not use jupyter.rich_display

We currently define displayas:

#' Display an object using any available reprs
#'
#' @param obj  The object to be displayed
#' @importFrom repr mime2repr repr_text
#' @export
display <- function (obj) {
    data <- namedlist()
    if (getOption('jupyter.rich_display')) {
        for (mime in getOption('jupyter.display_mimetypes')) {
            r <- mime2repr[[mime]](obj)
            if (!is.null(r)) data[[mime]] <- r
        }
    } else {
        data[['text/plain']] <- repr_text(obj)
    }
    publish_mimebundle(data)
}

I would like to shorten that to

#' Display an object using any available reprs
#'
#' @param obj  The object to be displayed
#' @importFrom repr mime2repr repr_text
#' @export
display <- function (obj) {
    data <- namedlist()
    for (mime in getOption('jupyter.display_mimetypes')) {
        r <- mime2repr[[mime]](obj)
        if (!is.null(r)) data[[mime]] <- r
    }
    publish_mimebundle(data)
}

This would mean that I can remove the auto rich display output (jupyter.rich_display = FALSE) and could still use display(something) and get all available output. That would in line with display_XXX which do not honor this option (and rightly so). It would also be more in line of the current doc string: "using any available reprs".

This would also mean that jupyter.rich_display would be an option of the kernel alone and not of the IRdisplay package. IMO it could then be renamed to jupyter.auto_rich_display.

remove svg from the plot display options

svg is simply not ready to be used for bigger plots :-(

This plot makes scrolling while the plot is visible a pain. Igraph also has some problems with it's svg based plotting. IMO it should be removed in irkernel (following the way it is done by the ipython kernel) or demoted in the notebook behind the bitmap based graphic formats.

library(magrittr)
library(ggplot2)
#options(jupyter.plot_mimetypes = c("text/plain", "image/png" )) # no more svg...
opt = theme(legend.position  = "none",
panel.background = element_rect(fill="violetred4"),
axis.ticks       = element_blank(),
panel.grid       = element_blank(),
axis.title       = element_blank(),
axis.text        = element_blank())
seq(from=-10, to=10, by = 0.05) %>%
expand.grid(x=., y=.) %>%
ggplot(aes(x=x, y=y)) +
geom_point(alpha=.1, shape=20, size=1, color="white", stroke=0) + opt

Lots of whitespace around grid useage...

Not sure where this comes from:

library(grid)
library(gridExtra)
d <- head(iris, 3)
g <- tableGrob(d)
grid.newpage()
grid.draw(g)

produces a plot which has lots of whitespace around it :-(

Happens with svg and svg removed

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.