jalapic
jalapic

Reputation: 14192

Using ggplot2 with Julia pluto notebook

I am working with a Pluto.jl notebook. I would like to use the ggplot2 R library to make some plots.

Following this example, if I run the following code in the Julia REPL then I can get a ggplot2 graph output.

using RCall
@rlibrary ggplot2
using DataFrames
df = DataFrame(v = [3,4,5], w = [5,6,7], x = [1,2,3], y = [4,5,6], z = [1,1,2])
ggplot(df, aes(x=:x,y=:y)) + geom_line()

Now, when I use the same code in a pluto.jl notebook (with each line being a separate cell), then I get the following error message:

enter image description here

Is there a way to get the ggplot2 image to appear inside the pluto notebook?

Similarly, if I just enter ggplot() into a cell, I get the same error, but ggplot not defined.

Upvotes: 5

Views: 779

Answers (2)

RikH
RikH

Reputation: 3404

As a workaround, it is possible to override Base.show manually (see Pluto.jl/sample/test1.jl) with

function Base.show(io::IO, ::MIME"image/png", p::RObject{VecSxp})
    (path, _) = mktemp()
    R"ggsave($path, plot=$p, device = 'png')"
    im = read(path)
    rm(path)
    write(io, im)
end

After that, cells which output anything of the type RObject{VecSxp} will show a PNG image:

Pluto notebook

Upvotes: 3

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42194

With @library Pluto.jl seems to be unable to find the R package.

However Pluto can handle this format:

@rimport ggplot2 as ggplot2

enter image description here

I managed to see the picture after clicking the "play" button 3 or 4 times. That is the end of good news - the Plut-RCall integration is kind of unstable. The graph shows in a separate Window that seems to hang - this is perhaps a story for opening an issue.

However what you can try to do is to save the image to a file and than visualize it:

begin
    ggplot2.ggplot(df, ggplot2.aes(x=:x, y=:y)) +  ggplot2.geom_line()
    ggplot2.ggsave("myplot.png")
    im1 = Images.load("myplot.png")
end

enter image description here

Upvotes: 3

Related Questions