1634
May 24, 2020, 10:42am
1
Hi,
I’d like to naming plot or variables in a for loop, interpolating corresponding id to their name, so later on I can use them in manner of my combination and order.
I checked related functions by ?name
but haven’t found what I want. Any suggestion?
for i in 1:5
p=plot(rand(10))
name(p)="p$i" #are there functions in julia can achieve this?
end
oheil
May 24, 2020, 11:00am
2
I think it is better to put the plot into an array:
E.g if you use the default backend (GR):
allPlots=Array{Plots.Plot{Plots.GRBackend},1}(undef,5)
for i in 1:5
allPlots[i]=plot(rand(10))
end
But if you insist in different variables for each plot you can use eval:
for i in 1:5
p="p$i=plot(rand(10))"
eval(Meta.parse(p))
end
Another way would be creating your own macro.
https://docs.julialang.org/en/v1/manual/metaprogramming/index.html#man-macros-1
2 Likes
1634
May 24, 2020, 11:51am
3
Thank you~ The fact that array can contain plots actually suprised me. Can array also contain dataframe like:
Array{DataFrames.DataFrame{Float64,2}, 1}(undef, 2,3,2)
oheil
May 24, 2020, 12:03pm
4
Sure, but it would be:
julia> aOfDf=Array{DataFrame}(undef,5)
5-element Array{DataFrame,1}:
#undef
#undef
#undef
#undef
#undef
julia> aOfDf[1]=DataFrame( [Float64,Float64],[:x,:y],3)
3×2 DataFrame
│ Row │ x │ y │
│ │ Float64 │ Float64 │
├─────┼─────────┼──────────────┤
│ 1 │ 0.0 │ 5.51928e-315 │
│ 2 │ 0.0 │ 8.0953e-316 │
│ 3 │ 0.0 │ 5.51928e-315 │
julia> aOfDf[2]=DataFrame( [Float64,Float64,Float64],[:x,:y,:z],3)
3×3 DataFrame
│ Row │ x │ y │ z │
│ │ Float64 │ Float64 │ Float64 │
├─────┼──────────────┼──────────────┼──────────────┤
│ 1 │ 1.16653e-315 │ 1.16653e-315 │ 1.13457e-315 │
│ 2 │ 6.91943e-316 │ 1.16653e-315 │ 6.91942e-316 │
│ 3 │ 6.92265e-316 │ 6.91943e-316 │ 6.91942e-316 │
julia> aOfDf
5-element Array{DataFrame,1}:
3×2 DataFrame
│ Row │ x │ y │
│ │ Float64 │ Float64 │
├─────┼─────────┼──────────────┤
│ 1 │ 0.0 │ 5.51928e-315 │
│ 2 │ 0.0 │ 8.0953e-316 │
│ 3 │ 0.0 │ 5.51928e-315 │
3×3 DataFrame
│ Row │ x │ y │ z │
│ │ Float64 │ Float64 │ Float64 │
├─────┼──────────────┼──────────────┼──────────────┤
│ 1 │ 1.16653e-315 │ 1.16653e-315 │ 1.13457e-315 │
│ 2 │ 6.91943e-316 │ 1.16653e-315 │ 6.91942e-316 │
│ 3 │ 6.92265e-316 │ 6.91943e-316 │ 6.91942e-316 │
#undef
#undef
#undef
So, you don’t have to specify the DataFrame for the Array, it’s just any DataFrame.
1 Like