How to rotate a bar graph in Plots.jl? - julia

Executing, in the REPL, after using Plots, bar(["One","Two","Three"], [1,2,3]) works. It produces the following:
However, I would like to have the x axis as the y, and the y as x. I just want that same data represented with horizontal bars, y'know? How would I go about doing this?
bar([1,2,3], ["One","Two","Three"]) gets:
ERROR: MethodError: no method matching AbstractFloat(::Type{String})
Closest candidates are:
AbstractFloat(::Bool) at float.jl:258
AbstractFloat(::Int8) at float.jl:259
AbstractFloat(::Int16) at float.jl:260
...
Stacktrace:
[1] float(::Type{T} where T) at ./float.jl:277
[2] _preprocess_barlike(::RecipesPipeline.DefaultsDict, ::Array{Float64,1}, ::Array{String,1}) at /home/dan/.julia/packages/Plots/GDtiZ/src/recipes.jl:509
[3] macro expansion at /home/dan/.julia/packages/Plots/GDtiZ/src/recipes.jl:359 [inlined]
[4] apply_recipe(::RecipesPipeline.DefaultsDict, ::Type{Val{:bar}}, ::Array{Float64,1}, ::Array{String,1}, ::Nothing) at /home/dan/.julia/packages/RecipesBase/aQmWx/src/RecipesBase.jl:281
[5] _process_seriesrecipe(::Plots.Plot{Plots.GRBackend}, ::RecipesPipeline.DefaultsDict) at /home/dan/.julia/packages/RecipesPipeline/tkFmN/src/series_recipe.jl:48
[6] _process_seriesrecipes!(::Plots.Plot{Plots.GRBackend}, ::Array{Dict{Symbol,Any},1}) at /home/dan/.julia/packages/RecipesPipeline/tkFmN/src/series_recipe.jl:25
[7] recipe_pipeline!(::Plots.Plot{Plots.GRBackend}, ::Dict{Symbol,Any}, ::Tuple{Array{Int64,1},Array{String,1}}) at /home/dan/.julia/packages/RecipesPipeline/tkFmN/src/RecipesPipeline.jl:96
[8] _plot!(::Plots.Plot{Plots.GRBackend}, ::Dict{Symbol,Any}, ::Tuple{Array{Int64,1},Array{String,1}}) at /home/dan/.julia/packages/Plots/GDtiZ/src/plot.jl:167
[9] plot(::Array{Int64,1}, ::Vararg{Any,N} where N; kw::Base.Iterators.Pairs{Symbol,Symbol,Tuple{Symbol},NamedTuple{(:seriestype,),Tuple{Symbol}}}) at /home/dan/.julia/packages/Plots/GDtiZ/src/plot.jl:57
[10] bar(::Array{Int64,1}, ::Vararg{Any,N} where N; kw::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}) at /home/dan/.julia/packages/RecipesBase/aQmWx/src/RecipesBase.jl:402
[11] bar(::Array{Int64,1}, ::Vararg{Any,N} where N) at /home/dan/.julia/packages/RecipesBase/aQmWx/src/RecipesBase.jl:402
[12] top-level scope at REPL[41]:1
Executing bar(y=["One","Two","Three"], x=[1,2,3])produces this:
I am thoroughly confused about what to try next.

bar(["One","Two","Three"], [1,2,3], orientation=:h)
"Horizontal or vertical orientation for bar types. Values :h, :hor, :horizontal correspond to horizontal (sideways, anchored to y-axis), and :v, :vert, and :vertical correspond to vertical (the default)."[1]
REF:
[1] http://docs.juliaplots.org/latest/generated/attributes_series/

Related

Julia Roots find_zero with ForwardDiff.Dual type?

I'm trying to apply automatic differentiation (ForwardDiff) to a function that contains an instance of find_zero (Roots) and am encountering an error that seems to relate to find_zero not accepting the ForwardDiff.Dual type.
Here's a (contrived) minimal working example that illustrates the issue:
using Distributions
using Roots
using StatsFuns
using ForwardDiff
function test_fun(θ::AbstractVector{T}) where T
μ,σ,p = θ;
z_star = find_zero(z -> logistic(z) - p, 0.0)
return pdf(Normal(μ,σ),z_star)
end
test_fun([0.0,1.0,0.75])
ForwardDiff.gradient(test_fun,[0.0,1.0,0.75])
This results in the following error:
ERROR: MethodError: no method matching Float64(::ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3})
Closest candidates are:
Float64(::Real, ::RoundingMode) where T<:AbstractFloat at rounding.jl:200
Float64(::T) where T<:Number at boot.jl:716
Float64(::Irrational{:invsqrt2}) at irrationals.jl:189
...
Stacktrace:
[1] convert(::Type{Float64}, ::ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}) at ./number.jl:7
[2] setproperty!(::Roots.UnivariateZeroState{Float64,ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}}, ::Symbol, ::ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}) at ./Base.jl:34
[3] update_state(::Roots.Secant, ::Roots.DerivativeFree{Roots.DerivativeFree{var"#5#6"{ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}}}}, ::Roots.UnivariateZeroState{Float64,ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}}, ::Roots.UnivariateZeroOptions{Float64,Float64,ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3},ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}}) at /bbkinghome/asharris/.julia/packages/Roots/TZpjF/src/derivative_free.jl:163
[4] find_zero(::Roots.Secant, ::Roots.AlefeldPotraShi, ::Roots.DerivativeFree{Roots.DerivativeFree{var"#5#6"{ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}}}}, ::Roots.UnivariateZeroState{Float64,ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}}, ::Roots.UnivariateZeroOptions{Float64,Float64,ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3},ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}}, ::Roots.NullTracks) at /bbkinghome/asharris/.julia/packages/Roots/TZpjF/src/find_zero.jl:868
[5] find_zero(::Roots.DerivativeFree{var"#5#6"{ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3}}}, ::Float64, ::Roots.Secant, ::Roots.AlefeldPotraShi; tracks::Roots.NullTracks, verbose::Bool, p::Nothing, kwargs::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}) at /bbkinghome/asharris/.julia/packages/Roots/TZpjF/src/find_zero.jl:689
[6] #find_zero#36 at /bbkinghome/asharris/.julia/packages/Roots/TZpjF/src/derivative_free.jl:123 [inlined]
[7] find_zero at /bbkinghome/asharris/.julia/packages/Roots/TZpjF/src/derivative_free.jl:120 [inlined]
[8] #find_zero#5 at /bbkinghome/asharris/.julia/packages/Roots/TZpjF/src/find_zero.jl:707 [inlined]
[9] find_zero at /bbkinghome/asharris/.julia/packages/Roots/TZpjF/src/find_zero.jl:707 [inlined]
[10] test_fun at ./REPL[7856]:3 [inlined]
[11] vector_mode_dual_eval at /bbkinghome/asharris/.julia/packages/ForwardDiff/QOqCN/src/apiutils.jl:37 [inlined]
[12] vector_mode_gradient(::typeof(test_fun), ::Array{Float64,1}, ::ForwardDiff.GradientConfig{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3,Array{ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3},1}}) at /bbkinghome/asharris/.julia/packages/ForwardDiff/QOqCN/src/gradient.jl:106
[13] gradient(::Function, ::Array{Float64,1}, ::ForwardDiff.GradientConfig{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3,Array{ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3},1}}, ::Val{true}) at /bbkinghome/asharris/.julia/packages/ForwardDiff/QOqCN/src/gradient.jl:19
[14] gradient(::Function, ::Array{Float64,1}, ::ForwardDiff.GradientConfig{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3,Array{ForwardDiff.Dual{ForwardDiff.Tag{typeof(test_fun),Float64},Float64,3},1}}) at /bbkinghome/asharris/.julia/packages/ForwardDiff/QOqCN/src/gradient.jl:17 (repeats 2 times)
[15] top-level scope at REPL[7858]:1
[16] run_repl(::REPL.AbstractREPL, ::Any) at /builddir/build/BUILD/julia/build/usr/share/julia/stdlib/v1.5/REPL/src/REPL.jl:288
I have limited experience using the FowardDiff package and am probably misunderstanding how the Dual type works, so I would really appreciate if someone knows how to solve this issue. Thanks so much!
z_star = find_zero(z -> logistic(z) - p, 0.0)
You have a fixed initial condition which is non-dual. Make it dual.
z_star = find_zero(z -> logistic(z) - p, zero(eltype(θ))

How to overload Base.show for custom array types?

Suppose I make my own custom vector type with it's own custom show method:
struct MyVector{T} <: AbstractVector{T}
v::Vector{T}
end
function Base.show(io::IO, v::MyVector{T}) where {T}
println(io, "My custom vector with eltype $T with elements")
for i in eachindex(v)
println(io, " ", v.v[i])
end
end
If I try making one of these objects at the REPL I get unexpected errors related to functions I never intended to call:
julia> MyVector([1, 2, 3])
Error showing value of type MyVector{Int64}:
ERROR: MethodError: no method matching size(::MyVector{Int64})
Closest candidates are:
size(::AbstractArray{T,N}, ::Any) where {T, N} at abstractarray.jl:38
size(::BitArray{1}) at bitarray.jl:77
size(::BitArray{1}, ::Integer) at bitarray.jl:81
...
Stacktrace:
[1] axes at ./abstractarray.jl:75 [inlined]
[2] summary(::IOContext{REPL.Terminals.TTYTerminal}, ::MyVector{Int64}) at ./show.jl:1877
[3] show(::IOContext{REPL.Terminals.TTYTerminal}, ::MIME{Symbol("text/plain")}, ::MyVector{Int64}) at ./arrayshow.jl:316
[4] display(::REPL.REPLDisplay, ::MIME{Symbol("text/plain")}, ::Any) at /Users/mason/julia/usr/share/julia/stdlib/v1.3/REPL/src/REPL.jl:132
[5] display(::REPL.REPLDisplay, ::Any) at /Users/mason/julia/usr/share/julia/stdlib/v1.3/REPL/src/REPL.jl:136
[6] display(::Any) at ./multimedia.jl:323
...
Okay, whatever so I'll implement Base.size so it'll leave me alone:
julia> Base.size(v::MyVector) = size(v.v)
julia> MyVector([1, 2, 3])
3-element MyVector{Int64}:
Error showing value of type MyVector{Int64}:
ERROR: getindex not defined for MyVector{Int64}
Stacktrace:
[1] error(::String, ::Type) at ./error.jl:42
[2] error_if_canonical_getindex(::IndexCartesian, ::MyVector{Int64}, ::Int64) at ./abstractarray.jl:991
[3] _getindex at ./abstractarray.jl:980 [inlined]
[4] getindex at ./abstractarray.jl:981 [inlined]
[5] isassigned(::MyVector{Int64}, ::Int64, ::Int64) at ./abstractarray.jl:405
[6] alignment(::IOContext{REPL.Terminals.TTYTerminal}, ::MyVector{Int64}, ::UnitRange{Int64}, ::UnitRange{Int64}, ::Int64, ::Int64, ::Int64) at ./arrayshow.jl:67
[7] print_matrix(::IOContext{REPL.Terminals.TTYTerminal}, ::MyVector{Int64}, ::String, ::String, ::String, ::String, ::String, ::String, ::Int64, ::Int64) at ./arrayshow.jl:186
[8] print_matrix at ./arrayshow.jl:159 [inlined]
[9] print_array at ./arrayshow.jl:308 [inlined]
[10] show(::IOContext{REPL.Terminals.TTYTerminal}, ::MIME{Symbol("text/plain")}, ::MyVector{Int64}) at ./arrayshow.jl:345
[11] display(::REPL.REPLDisplay, ::MIME{Symbol("text/plain")}, ::Any) at /Users/mason/julia/usr/share/julia/stdlib/v1.3/REPL/src/REPL.jl:132
[12] display(::REPL.REPLDisplay, ::Any) at /Users/mason/julia/usr/share/julia/stdlib/v1.3/REPL/src/REPL.jl:136
[13] display(::Any) at ./multimedia.jl:323
...
Hmm, now it wants getindex
julia> Base.getindex(v::MyVector, args...) = getindex(v.v, args...)
julia> MyVector([1, 2, 3])
3-element MyVector{Int64}:
1
2
3
What? That wasn't the print formatting I told it to do! what's going on here?
The problem is that in julia, Base defines a method Base.show(io::IO ::MIME"text/plain", X::AbstractArray) which is actually more specific than the Base.show(io::IO, v::MyVector) for the purposes of display. This section of the julia manual describes the sort of custom printing that AbstractArray uses. So if we want to use our custom show method, we instead need to do
julia> function Base.show(io::IO, ::MIME"text/plain", v::MyVector{T}) where {T}
println(io, "My custom vector with eltype $T and elements")
for i in eachindex(v)
println(io, " ", v.v[i])
end
end
julia> MyVector([1, 2, 3])
My custom vector with eltype Int64 and elements
1
2
3
See also: https://discourse.julialang.org/t/extending-base-show-for-array-of-types/31289

Largest prime factor algorithm returning out of memory error

I'm trying to learn Julia via project Euler. And for the largest prime factor problem I ran into an issue with out of memory error and I don't understand why.
I have tried the same solution in Python and had no issues.
function Primes(n)
numbers = Set{Int64}(2:n)
primes = Int64[]
while length(numbers)!=0
p = pop!(numbers,minimum(numbers))
push!(primes,p)
if length(numbers)!=0
numbers = setdiff(numbers,Set{Int64}(2*p:p:maximum(numbers)))
end
end
return primes
end
function LPF(n)
primes = Primes(n//2)
for p in primes
if n%p==0
return p
end
end
end
LPF(600851475143)
this is my error message:
OutOfMemoryError()
Stacktrace:
[1] _growend! at .\array.jl:811 [inlined]
[2] resize! at .\array.jl:1003 [inlined]
[3] rehash!(::Dict{Int64,Nothing}, ::Int64) at .\dict.jl:183
[4] sizehint! at .\dict.jl:242 [inlined]
[5] sizehint! at .\set.jl:64 [inlined]
[6] union!(::Set{Int64}, ::UnitRange{Rational{Int64}}) at .\abstractset.jl:79
[7] Type at .\set.jl:10 [inlined]
[8] Primes(::Rational{Int64}) at .\In[14]:2
[9] LPF(::Int64) at .\In[24]:2
[10] top-level scope at In[25]:1

No method matching ^

I created a UnitRange in Julia and trying to create a plot of x with respect to x and x ^ 2. I have written the following code.
x = [-10:10]
p1 = plot(x, x)
p2 = plot(x, x.^2)
I am getting the following error:
MethodError: no method matching ^(::UnitRange{Int64}, ::Int64)
Closest candidates are:
^(!Matched::Float16, ::Integer) at math.jl:795
^(!Matched::Missing, ::Integer) at missing.jl:120
^(!Matched::Missing, ::Number) at missing.jl:93
...
Stacktrace:
[1] _broadcast_getindex at ./none:0 [inlined]
[2] getindex at ./broadcast.jl:515 [inlined]
[3] copy at ./broadcast.jl:790 [inlined]
[4] materialize(::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1},Nothing,typeof(Base.literal_pow),Tuple{Base.RefValue{typeof(^)},Array{UnitRange{Int64},1},Base.RefValue{Val{2}}}}) at ./broadcast.jl:756
[5] top-level scope at In[18]:3
What is the mistake in my code?
You can change:
x.^2
to:
x[1].^2

LoadError: type DataFrame has no field x

I have converted a perfectly working map into a pmap
squashed_groups = pmap(group ->
reduce(squash,
DataFrame(eltypes(o), names(o), 0),
eachrow(group)
),
groups)
Apart from the fact that it doesn't seem to engage in any parallelism -- but I will concede that the groups are mostly small -- I get the following error
ERROR: LoadError: type DataFrame has no field x
Stacktrace:
[1] copy!(::Array{DataFrames.AbstractDataFrame,1}, ::Base.Generator{Array{DataFrames.AbstractDataFrame,1},DataFrames.##34#35{Base.##569#571}}) at ./abstractarray.jl:572
[2] _collect(::Type{DataFrames.AbstractDataFrame}, ::Base.Generator{Array{DataFrames.AbstractDataFrame,1},DataFrames.##34#35{Base.##569#571}}, ::Base.HasShape) at ./array.jl:363
[3] map(::Base.##569#571, ::DataFrames.GroupApplied) at /Users/morpheu5/.julia/v0.6/DataFrames/src/groupeddataframe/grouping.jl:184
[4] maptwice(::Function, ::Channel{Any}, ::Array{Any,1}, ::DataFrames.GroupedDataFrame, ::Vararg{DataFrames.GroupedDataFrame,N} where N) at ./asyncmap.jl:188
[5] wrap_n_exec_twice(::Channel{Any}, ::Array{Any,1}, ::Base.Distributed.##204#207{WorkerPool}, ::Function, ::DataFrames.GroupedDataFrame, ::Vararg{DataFrames.GroupedDataFrame,N} where N) at ./asyncmap.jl:154
[6] #async_usemap#553(::Function, ::Void, ::Function, ::##9#10, ::DataFrames.GroupedDataFrame, ::Vararg{DataFrames.GroupedDataFrame,N} where N) at ./asyncmap.jl:103
[7] (::Base.#kw##async_usemap)(::Array{Any,1}, ::Base.#async_usemap, ::Function, ::DataFrames.GroupedDataFrame, ::Vararg{DataFrames.GroupedDataFrame,N} where N) at ./<missing>:0
[8] (::Base.#kw##asyncmap)(::Array{Any,1}, ::Base.#asyncmap, ::Function, ::DataFrames.GroupedDataFrame) at ./<missing>:0
[9] #pmap#203(::Bool, ::Int64, ::Void, ::Array{Any,1}, ::Void, ::Function, ::WorkerPool, ::Function, ::DataFrames.GroupedDataFrame) at ./distributed/pmap.jl:126
[10] pmap(::WorkerPool, ::Function, ::DataFrames.GroupedDataFrame) at ./distributed/pmap.jl:101
[11] #pmap#213(::Array{Any,1}, ::Function, ::Function, ::DataFrames.GroupedDataFrame) at ./distributed/pmap.jl:156
[12] pmap(::Function, ::DataFrames.GroupedDataFrame) at ./distributed/pmap.jl:156
[13] include_from_node1(::String) at ./loading.jl:569
[14] include(::String) at ./sysimg.jl:14
[15] process_options(::Base.JLOptions) at ./client.jl:305
[16] _start() at ./client.jl:371
I couldn't figure out that that means. I even checked for any places where I could have used an x somewhere and changed those, but the error message doesn't change. The inner reduce is a bit complicated, but works using the non-parallel map -- as in, it produces the expected result.
Is this a case of me having read all the docs and having understood none of them, or is this a bug somewhere in Julia? I'm running 0.6.0 on x86_64-apple-darwin13.4.0.

Resources