KarthikRIyer/swiftplot

Display plots in Jupyter

KarthikRIyer opened this issue · 6 comments

Display plots in Jupyter

@marcrasi
Is there a way to find out if the code is running in the terminal or jupyter notebook/colab? I found some ways in python on stackoverflow. I thought I could do the same in swift.
I wrote this to try:

import Python

func type() {
    do {
        let ipython = Python.import("IPython")
        print(ipython.config)
    }
    catch {
      print("here")
    }
}

type()

But this gave me a fatal error both in colab and terminal.

Fatal error: Could not access PythonObject member 'config': file /swift-base/swift/stdlib/public/Python/Python.swift, line 537
Illegal instruction (core dumped)

This is what I was referring to: https://stackoverflow.com/a/24937408/9126612

I think that you should not put the "draw in jupyter" logic inside this library -- you should instead provide an interface in this library that lets jupyter extract the data that it needs, and then add some code to swift-jupyter that actually draws it. This way, the code won't have to detect whether it's running inside a notebook. It can just serve data through its interface, and the client can worry about displaying it in a way that's appropriate for the environment.

The simplest way to do this would be to add a base64Png() method to some renderers that returns a string. Then add a display(base64Png: String) function to swift-jupyter's EnableIPythonDisplay.swift. Users would then be able to do

let renderer = ...
let plot = ...
plot.drawGraph(renderer: renderer)
display(base64Png: renderer.base64Png())

@marcrasi I've opened PR for the display function in the swift-jupyter repo

@marcrasi should I make the changes suggested by rxwei and open another PR?

Yes please, that would be good!