Plotting Method error using PyPlot in IJulia - matplotlib

I am trying to plot a function using PyPlot on an IJulia notebook, but I keep obtaining error messages.
When I ran this code:
function gtest2(x)
6.34*(log2(1+exp(10.0*(x+0.5))))^0.8
end
using PyPlot
x = -1.0:0.1:1.0;
plot(x, gtest2(x));
I got errors like these:
MethodError: no method matching ^(::Array{Float64,1}, ::Float64)
Closest candidates are: ^(::Float64, ::Float64) at math.jl:355 ...
I tried to defined a different type of variable while defining my function using gtest2(x::Number) or gtest2(x::Float64) but I have the same errors.
It does the same using linespace instead of -1.0:0.1:1.0. I understand that the format the function sees in input does not match the definition but I don't get what I'm doing wrong because simple functions work:
function f(x)
x
end
plot(x,f(x))
Why am I getting those errors in the first case?
I am using IJulia notebook 0.5.1 on safari.

Your code doesn't properly handle vectors thus you need to either change gtest
using the . vectorization syntax
function gtest2(x)
6.34*(log2.(1 + exp.(10.0*(x + 0.5)))).^0.8
end
or even easier use the dot vectorization as follows
plot(x, gtest2.(x));
To learn more about dot vectorization please see the following in the docs: https://docs.julialang.org/en/latest/manual/functions.html#man-vectorized-1

The first definition works also with:
map(gtest2, x)
or
gtest2.(x)

Related

Syntax error when using imported Scipy functions in Julia

I have succesfully imported Scipy Optimize's function minimize to Julia, but when I try to use it so that I specify constraints to it:
julia> #pyimport scipy.optimize.minimize as so
julia> so.minimize(f, x0,
constraints={"type": "ineq", "fun": g},
options={"maxiter": 1000})
Julia throws an error about the curly braces:
ERROR: LoadError: syntax: { } vector syntax is discontinued
Anyone having an idea of how the minimize function could be used properly in Julia?
I now realized that the curly brackets present dicts in Python and the Julia-version should therefore look like:
julia> so.minimize(objective_function, coords,
constraints = Dict("type" => "ineq", "fun" => g),
options = Dict("maxiter" => 1000))
So my guess is now that even though the function comes from Scipy, the input arguments need to be Julia syntax.

Logarithmic scaling / colorbar in Julia using PyPlot (matplotlib)

I am using Julia 0.5 and the latest version of PyPlot.
I am printing an 2D-Array using plot.pcolorand it works pretty good. But now I have data that needs a logarithmic scaling. I searched on the web and what I found was an example using
plt.pcolor(X, Y, Z1, norm=LogNorm(vmin=Z1.min(), vmax=Z1.max()), cmap='PuBu_r')
But since LogNorm seems to be a python function ist doesn't work in Julia. Does anyone have an idea what I can hand over to norm=to get a logarithmic scaling?
An example would be:
using PyPlot
A = rand(20,20)
figure()
PyPlot.pcolor(A, cmap="PuBu_r")
colorbar()
Matplotlib fields and methods can be accessed using the
matplotlib[:colors][:LogNorm]
syntax (i.e. for the corresponding matplotlib.colors.LogNorm object).
UPDATE: Thank you for your mwe. Based on that example, I managed to make it work like this:
PyPlot.pcolor(A, norm=matplotlib[:colors][:LogNorm](vmin=minimum(A), vmax=maximum(A)), cmap="PuBu_r")

Julia PyPlot can't create quadratic function

I'm trying to learn to plot things with Julia using PyPlot, and I tried to plot a quadratic function. It does not like how I'm squaring x. I tried using x**2 and x*x, and the compiler did not accept those either. What should I be using to square x?
Thanks
Code # line 7:
x1 = linspace(0,4*pi, 500); y1 = x^2
Error:
LoadError: MethodError: `*` has no method matching *(::LinSpace{Float64},
::LinSpace{Float64})
Closest candidates are:
*(::Any, ::Any, !Matched::Any, !Matched::Any...)
*{T}(!Matched::Bidiagonal{T}, ::AbstractArray{T,1})
*(!Matched::Number, ::AbstractArray{T,N})
...
in power_by_squaring at intfuncs.jl:80
in ^ at intfuncs.jl:108
in include_string at loading.jl:282
in include_string at C:\Users\User\.julia\v0.4\CodeTools\src\eval.jl:32
in anonymous at C:\Users\User\.julia\v0.4\Atom\src\eval.jl:84
in withpath at C:\Users\User\.julia\v0.4\Requires\src\require.jl:37
in withpath at C:\Users\User\.julia\v0.4\Atom\src\eval.jl:53
[inlined code] from C:\Users\User\.julia\v0.4\Atom\src\eval.jl:83
in anonymous at task.jl:58
while loading C:\Users\User\Desktop\Comp Sci\Class\plotTest, in expression
starting on line 7
To square every element of an array, use x.^2.
You are trying to square all of the elements of an array. This means you need to use the element-wise version x.^2.

PyPlot Error in Julia: type PyObject has no field set_yscale

I am programming in Julia but using PyPloy library. I want to plot an histogram with log y-axis. But when I use the following code:
using PyPlot
List = [rand() for i = 1:100]
plt.hist(List)
plt.gca().set_yscale("log")
I get the following error:
type PyObject has no field set_yscale
while loading In[45], in expression starting on line 3
in getindex at /home/rm/.julia/v0.4/PyCall/src/PyCall.jl:642
in pysequence_query at /home/rm/.julia/v0.4/PyCall/src/conversions.jl:743
in pytype_query at /home/rm/.julia/v0.4/PyCall/src/conversions.jl:759
in convert at /home/rm/.julia/v0.4/PyCall/src/conversions.jl:808
in pycall at /home/rm/.julia/v0.4/PyCall/src/PyCall.jl:812
in fn at /home/rm/.julia/v0.4/PyCall/src/conversions.jl:181
in close_queued_figs at /home/rm/.julia/v0.4/PyPlot/src/PyPlot.jl:295
Is this a path error? If so, is there a simpler way to do a log-log plot with a different command?
Thanks in advance.
I feel like this should be more prominently explained in the documentation, but if you scroll down to the bottom of the Readme for PyCall (which PyPlot uses) it says:
Important: The biggest difference from Python is that object attributes/members are accessed with o[:attribute] rather than o.attribute, so that o.method(...) in Python is replaced by o[:method](...)
So, as #jverzani mentioned, after you call any module-level function from PyPlot that returns an object, that object is a PyObject and all of the attributes and methods have to be called using the bracket notation with a symbol.

PathPatch object in julia with PyPlot

I was trying to reproduce this example from the matplotlib website using the PyPlot package for Julia. As far as I know, the PyPlot is essentialy the matplotlib.pyplot module, so I imported the other modules of matplotlib that I needed (with the #pyimport macro):
using PyCall
#pyimport matplotlib.path as mpath
#pyimport matplotlib.patches as mpatches
Then I proceed to define the path object:
Path = mpath.Path
but then I get:
fn (generic function with 1 method) .
As if I had defined a function. Moreover, when I assign the path_data I get the following error:
ERROR: type Function has no field MOVETO
Of course, that's due to Path, which Julia tries as a function and not as a type or something like that. As you might guess the same happens when I try to define the variable patch .
So, there are incompatibilities of modules from matplotlib different to pyplot for Julia since the expected objects (types) are taken as functions. This behaviour can be expected if it were different the PyPlot.jl file wouldn't be needed.
My questions are:
-Am I doing something wrong?
-Is there a simple way to make it works?
-Do you know another package for Julia in which I can define patches and work in a similar way to matplotlib?
I have in mind to do this kind of animations.
Thanks for your ideas.
You need to get the "raw" Python object for Path. By default, PyCall converts Python type objects into functions (which call the corresponding constructor), but then you cannot access static members of the class.
Instead, do e.g. Path = mpath.pymember("Path") to get the "raw" PyObject, and then you can do Path["MOVETO"] or Path[:MOVETO] to access the MOVETO member.
(This difficulty will hopefully go away in Julia 0.4 once something like https://github.com/JuliaLang/julia/pull/8008 gets merged (so that we can make PyObjects callable directly.)