4

I have built a GUI using Glade, GTK and Julia. I want to add a plot in my GUI (in my window / layout) but cannot find a way to add a plot as a widget. How can I implement a plot in my GUI using Plots.jl?

Adding the following does not make anything appear in my GUI layout

x = 1:10; y = rand(10, 3) #
plot(x, y)
aight101
  • 63
  • 6

1 Answers1

2

You can have Plots write the image as a MIME in-memory image and then in the Canvas draw update have Gtk load that image:

using Cairo
using Gtk
using Plots

const io = PipeBuffer()

histio(n) = show(io, MIME("image/png"),  histogram(randn(n)))

function plotincanvas(h = 900, w = 800)
    win = GtkWindow("Normal Histogram Widget", h, w) |> (vbox = GtkBox(:v) |> (slide = GtkScale(false, 1:500)))
    Gtk.G_.value(slide, 250.0)
    can = GtkCanvas()
    push!(vbox, can)
    set_gtk_property!(vbox, :expand, can, true)
    @guarded draw(can) do widget
        ctx = getgc(can)
        n = Int(Gtk.GAccessor.value(slide))
        histio(n)
        img = read_from_png(io)
        set_source_surface(ctx, img, 0, 0)
        paint(ctx)
    end
    id = signal_connect((w) -> draw(can), slide, "value-changed")
    showall(win)
    show(can)
end

plotincanvas()

I am sure that there is also a way to transfer the image data directly, without show(), if you knew the underlying data formats. This method avoids any need for explicit conversions.

Bill
  • 5,600
  • 15
  • 27
  • Would this method work for real time plotting as well? – aight101 Jun 13 '22 at 16:34
  • Yes, as long as the computer can update the point calculations in real time as well. – Bill Jun 13 '22 at 17:09
  • I've seen this strategy a couple times on gtk.jl. I assume this is going to be very hard on a hard drive unless there's an integrated way to include a plot. Maybe open a feature request? – Will Jul 09 '22 at 02:06
  • There is a way to do it with IOBuffer, though I had to get the rewinding of the buffer right (rewind with seekstart() not once but twice). I will update the answer to reflect that. – Bill Jul 10 '22 at 19:05
  • I put in a PR to Plots (# 4269). – Bill Jul 10 '22 at 19:41