Set axis origin using PyPlot plot in Julia - plot

I am completely new to Julia. I am using the PyPlot package in Julia and am just trying to set my x and y axis origin to 0 and 0 respectively. At the moment it just chooses where the origin will be based on the values of the points I'm plotting.
plot(x1,y1,".")
xlabel("X1")
ylabel("Y1")
title("First Line")
grid("on")
I have tried the following but it doesn't work.
change matplotlib axis settings

Using PyPlot in Julia is different than matplotlib in Python. You are looking for the Julia equivalent of setting limits on axis. I've found this useful github repo that might be of use to you.
Here is how you can add custom limits to the y axis:
using PyPlot
x1 = rand(50, 1) .* 30 .+ 50
y1 = rand(50, 1) .* 30 .+ 100
plot(x1, y1)
# get the current axis argument of the plot
ax = gca()
# add new limits from 0 - 100
ax[:set_ylim]([0,100])

The syntax for using PyPlot in Julia is a bit different from Python.
This is a result of the fact that (currently) you cannot use obj.f() to access the method (function) f() inside an object obj in Julia, which PyPlot uses heavily.
To get around this, obj.f() in Python is replaced by obj[:f]() in Julia; note the :.
So ax.spines in Python becomes
ax[:spines]
in Julia.
As noted by the other poster, you must first do ax = gca() to store the current axis object in the variable ax.
If you do this at the Julia REPL or in a Jupyter notebook, you will see
julia> ax = gca()
PyObject <matplotlib.axes._subplots.AxesSubplot object at 0x31f854550>
julia> ax[:spines]
Dict{Any,Any} with 4 entries:
"left" => PyObject <matplotlib.spines.Spine object at 0x31f854c10>
"bottom" => PyObject <matplotlib.spines.Spine object at 0x31f854f50>
"right" => PyObject <matplotlib.spines.Spine object at 0x31f854dd0>
"top" => PyObject <matplotlib.spines.Spine object at 0x31f86e110>
showing that ax[:spines] is a dictionary. (I did not previously know about this. This is the advantage of having an interactive session -- you can just ask Julia what you need to know. This is called "introspection".)
Following the Python answer linked to in the original question, you then need to replace ax.spines['left'].set_position('zero') in Python by the following in Julia:
ax[:spines]["left"][:set_position]("zero")
Again, the set_position method inside the object ax[:spines]["left"] is called. Note also that strings in Julia must have ", not '.

Related

Julia/Flux creating a model correctly - using Chain Embedding layer reshaping & Dense layers

I am trying to follow an old article about word embedding in Julia language with Flux: https://spcman.github.io/getting-to-know-julia/deep-learning/nlp/flux-embeddings-tutorial-1/
As it is an old outdated article I managed to handle the embedding layer correctly using the new embedding layer of Flux (0.13.11). The Chain looks like this:
embedding = Flux.Embedding(vocab_size => max_features, init=Flux.glorot_normal)
model = Chain(embedding(Flux.onehotbatch(reshape(x, pad_size*N), 0:vocab_size-1)),
x -> reshape(x, max_features, pad_size, N),
x -> mean(x, dims=2),
x -> reshape(x, 8, 10),
Dense(8, 1),
)
When I try to check the model my calling model(x) I get:
ERROR: MethodError: objects of type Matrix{Float32} are not callable
Use square brackets [] for indexing an Array.
My guess that the problem somehow connected to the reshaping.
I am new to both Julia & Flux so sorry if the question is basic.
Any clue what should I do?

plotting a python function that uses an array

In sagemath, I would like to plot the following function foo (Coef is an array that is big enough) :
def foo(x):
x_approx = floor (x*4)
return Coef[x_approx]
I wanted to use the command plot(foo(x), (x,0,0.1)).
But I got the error unable to convert floor(4*x) to an integer.
Whereas when `foo is not using an array, it works:
def foo(x):
x_approx = floor (x*4)
return 4*x_approx
Use plot(foo, (x, 0, 0.1)) instead (that is, replace foo(x) with foo). If you use foo(x), then Sage tries to evaluate foo(x) first, in which case it treats x as a symbolic variable and can't turn it into a number to plot. If you use foo, then it knows to treat it as a plottable/callable function, and it does the right thing.
Edit: I think the issue is that for plotting, Sage requires a certain type of function, a symbolic function, and using a Python construct like Coef[...] doesn't fit into that framework.

Julia: Converting PyObject to an Array

In Julia, I am calling a Python module pandas_datareader to download data from the web:
using PyCall
#pyimport datetime
#pyimport pandas_datareader.data as web
gdp = web.DataReader("GDPCA","fred",start=datetime.datetime(1929,1,1))
The variable gdp is a PyObject object. As such, I cannot manipulate it (take logs for example). How do I convert it to an array? I tried convert(Array{Float64,2},gdp), but it only crashes Julia.
Thanks!
The #pyimport macro is used to manipulate the Python objects in this case, pandas DataFrame, via the PyObject type. Given o::PyObject, o[:attribute] is equivalent to o.attribute in Python, with automatic type conversion. So the below snippet shows how to obtain a Julia array from a call to Python function,
julia> using PyCall
julia> #pyimport datetime
julia> gdp = web.DataReader("GDPCA","fred",start=datetime.datetime(1929,1,1))
julia> typeof(gdp)
PyCall.PyObject
julia> gdp[:values]
87x1 Array{Float64,2}:
1056.6
966.7
904.8
788.2
778.3
...

How do I organize complex data in julia

I decided to try julia a few days ago and tried to translate one of my python projects to julia. I understand that using the type system is crucial for good performance. However, I have something like this in python:
class Phonon(object):
# it has an attribute called D which looks like
# D = {'on_site': [D00, D11, D22, D33 ...], 'lead':{'l': [Dl00, Dl01, Dl11], 'r': [Dr00, Dr01, Dr11]},'couple': [D01, D12, D23 ...], 'lead_center':{'l': Dlcl, 'r': Dlcr}}
# all D00, D11, D22 matrices are numpy arrays
If I translate this into julia, it would be:
type Phonon:
D::Dict{ASCIIString, Any}
end
It seems that compiler cannot get much infomation about what phonons are. So my question is: How do julia people organize their complex data?
if i understood you properly, you may want something like this:
type PhononDict{T<:Number}
on_site::Vector{Matrix{T}}
lead::Dict{ASCIIString, Vector{Matrix{T}}}
couple::Vector{Matrix{T}}
lead_center::Dict{ASCIIString, Matrix{T}}
end
i assumed that the element type of your numpy array <: Number, you can adjust it to something like T<:Union{Int64, Float64} instead.
the key problem here is lead::Dict, so D::Dict{ASCIIString, Any}:
julia> typejoin(Array, Dict)
Any
i suggest to change D into a composite type and then you can pass more info to compiler. more information concerning parametric types.

Assert type information onto computed results in Julia

Problem
I read in an array of strings from a file.
julia> file = open("word-pairs.txt");
julia> lines = readlines(file);
But Julia doesn't know that they're strings.
julia> typeof(lines)
Array{Any,1}
Question
Can I tell Julia this somehow?
Is it possible to insert type information onto a computed result?
It would be helpful to know the context where this is an issue, because there might be a better way to express what you need - or there could be a subtle bug somewhere.
Can I tell Julia this somehow?
No, because the readlines function explicitly creates an Any array (a = {}): https://github.com/JuliaLang/julia/blob/master/base/io.jl#L230
Is it possible to insert type information onto a computed result?
You can convert the array:
r = convert(Array{ASCIIString,1}, w)
Or, create your own readstrings function based on the link above, but using ASCIIString[] for the collection array instead of {}.
Isaiah is right about the limits of readlines. More generally, often you can say
n = length(A)::Int
when generic type inference fails but you can guarantee the type in your particular case.
As of 0.3.4:
julia> typeof(lines)
Array{Union(ASCIIString,UTF8String),1}
I just wanted to warn against:
convert(Array{ASCIIString,1}, lines)
that can fail (for non-ASCII) while I guess, in this case nothing needs to be done, this should work:
convert(Array{UTF8String,1}, lines)

Resources