6
votes

I just installed PyPlot in Julia. It's working fine when I run it from julia's interactive environment. But when I make a .jl script an run from bash the plot graphics does not displays.

I'm familiear with matplotlib (pylab) where show() command is used to view the figures. I probably don't undestand the readme of PyPlot here https://github.com/stevengj/PyPlot.jl

You can get the current figure as a Figure object (a wrapper around matplotlib.pyplot.Figure) by calling gcf(). The Figure type supports Julia's multimedia I/O API, so you can use display(fig) to show a fig::PyFigure

If I run this script:

using PyPlot
x = linspace(0,2*pi,1000); y = sin(3*x + 4*cos(2*x));
plot(x, y, color="red", linewidth=2.0, linestyle="--")
title("A sinusoidally modulated sinusoid")
fig1 = gcf()
display(fig1)

I get no graphics on the screen, just text output with address of the figure object

$ julia pyplottest.jl
Loading help data...
Figure(PyObject <matplotlib.figure.Figure object at 0x761dd10>)

I'm also not sure why it take so long time and what "Loading help data..." does mean

if I run the same script from inside of Julia evironment using include("pyplottest.jl") the plot does shows fine

2

2 Answers

4
votes

display only works if you are running an environment that supports graphical I/O, like IJulia, but even there you don't really need to call it directly (the plot is displayed automatically when an IJulia cell finishes executing).

You can do show() just like in Python. However, PyPlot loads Matplotlib in interactive mode, with the GUI event loop running in the background, so show() is non-blocking and doesn't really do anything. One option is to just do

using PyPlot
x = linspace(0,2*pi,1000); y = sin(3*x + 4*cos(2*x));
plot(x, y, color="red", linewidth=2.0, linestyle="--")
title("A sinusoidally modulated sinusoid")
print("Hit <enter> to continue")
readline()

to pause.

If you just want to do non-interactive Matplotlib, you don't need the PyPlot package at all. You can just do:

using PyCall
@pyimport matplotlib.pyplot as plt
x = linspace(0,2*pi,1000); y = sin(3*x + 4*cos(2*x));
plt.plot(x, y, color="red", linewidth=2.0, linestyle="--")
plt.title("A sinusoidally modulated sinusoid")
plt.show()

and the show() command will block until the user closes the plot window.

(Possibly I should add an option to PyPlot to load it in non-interactive mode.)

2
votes

If you are not in REPL or interactive mode (i.e. using sublime like me) then you have to add plt[:show]() to see the plot.

I asked the same question a while ago: https://groups.google.com/forum/#!topic/julia-users/A2JbZMvMJhY