forked from MakieOrg/Makie.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
figureplotting.jl
311 lines (258 loc) · 11.1 KB
/
figureplotting.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
struct AxisPlot
axis::Any
plot::AbstractPlot
end
struct FigureAxis
figure::Figure
axis::Any
end
Base.show(io::IO, fap::FigureAxisPlot) = show(io, fap.figure)
Base.show(io::IO, ::MIME"text/plain", fap::FigureAxisPlot) = print(io, "FigureAxisPlot()")
Base.iterate(fap::FigureAxisPlot, args...) = iterate((fap.figure, fap.axis, fap.plot), args...)
Base.iterate(ap::AxisPlot, args...) = iterate((ap.axis, ap.plot), args...)
get_scene(ap::AxisPlot) = get_scene(ap.axis.scene)
function _validate_nt_like_keyword(@nospecialize(kw), name)
if !(kw isa NamedTuple || kw isa AbstractDict{Symbol} || kw isa Attributes)
throw(ArgumentError("""
The $name keyword argument received an unexpected value $(repr(kw)).
The $name keyword expects a collection of Symbol => value pairs, such as NamedTuple, Attributes, or AbstractDict{Symbol}.
The most common cause of this error is trying to create a one-element NamedTuple like (key = value) which instead creates a variable `key` with value `value`.
Write (key = value,) or (; key = value) instead."""))
end
end
function _disallow_keyword(kw, attributes)
if haskey(attributes, kw)
throw(ArgumentError("You cannot pass `$kw` as a keyword argument to this plotting function. Note that `axis` can only be passed to non-mutating plotting functions (not ending with a `!`) that implicitly create an axis, and `figure` only to those that implicitly create a `Figure`."))
end
end
# For plots that dont require an axis,
# E.g. BlockSpec
struct FigureOnly end
function args_preferred_axis(::Type{<:Union{Wireframe,Surface,Contour3d}}, x::AbstractArray, y::AbstractArray,
z::AbstractArray)
return all(x -> z[1] ≈ x, z) ? Axis : LScene
end
args_preferred_axis(x) = nothing
function args_preferred_axis(@nospecialize(args...))
# Fallback: check each single arg if they have a favorite axis type
for arg in args
r = args_preferred_axis(arg)
isnothing(r) || return r
end
return nothing
end
args_preferred_axis(::AbstractVector, ::AbstractVector, ::AbstractVector, ::Function) = LScene
args_preferred_axis(::AbstractArray{T,3}) where {T} = LScene
function args_preferred_axis(::AbstractVector{<:Union{AbstractGeometry{DIM},GeometryBasics.Mesh{DIM}}}) where {DIM}
return DIM === 2 ? Axis : LScene
end
function args_preferred_axis(::Union{AbstractGeometry{DIM},GeometryBasics.Mesh{DIM}}) where {DIM}
return DIM === 2 ? Axis : LScene
end
args_preferred_axis(::AbstractVector{<:Point3}) = LScene
args_preferred_axis(::AbstractVector{<:Point2}) = Axis
preferred_axis_type(::Volume) = LScene
preferred_axis_type(::Union{Image,Heatmap}) = Axis
function preferred_axis_type(p::Plot{F}) where F
# Otherwise, we check the arguments
input_args = map(to_value, p.args)
result = args_preferred_axis(Plot{F}, input_args...)
isnothing(result) || return result
conv_args = map(to_value, p.converted)
result = args_preferred_axis(Plot{F}, conv_args...)
isnothing(result) && return Axis # Fallback to Axis if nothing found
return result
end
to_dict(dict::Dict) = dict
to_dict(nt::NamedTuple) = Dict{Symbol,Any}(pairs(nt))
to_dict(attr::Attributes) = attributes(attr)
function extract_attributes(dict, key)
attributes = pop!(dict, key, Dict{Symbol,Any}())
_validate_nt_like_keyword(attributes, key)
return to_dict(attributes)
end
function create_axis_for_plot(figure::Figure, plot::AbstractPlot, attributes::Dict)
axis_kw = extract_attributes(attributes, :axis)
AxType = if haskey(axis_kw, :type)
pop!(axis_kw, :type)
else
preferred_axis_type(plot)
end
if AxType == FigureOnly # For FigureSpec, which creates Axes dynamically
return nothing
end
bbox = pop!(axis_kw, :bbox, nothing)
return _block(AxType, figure, [], axis_kw, bbox)
end
function create_axis_like(plot::AbstractPlot, attributes::Dict, ::Nothing)
figure_kw = extract_attributes(attributes, :figure)
figure = Figure(; figure_kw...)
ax = create_axis_for_plot(figure, plot, attributes)
if isnothing(ax) # For FigureSpec
return figure
else
figure[1, 1] = ax
return FigureAxis(figure, ax)
end
end
MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, s::Union{Plot, Scene}) = s
function MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, ::Nothing)
figure = current_figure()
isnothing(figure) && error("There is no current figure to plot into.")
_disallow_keyword(:figure, attributes)
ax = current_axis(figure)
isnothing(ax) && error("There is no current axis to plot into.")
_disallow_keyword(:axis, attributes)
return ax
end
function MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, gp::GridPosition)
_disallow_keyword(:figure, attributes)
c = contents(gp; exact=true)
if !(length(c) == 1 && can_be_current_axis(c[1]))
error("There needs to be a single axis-like object at $(gp.span), $(gp.side) to plot into.\nUse a non-mutating plotting command to create an axis implicitly.")
end
ax = first(c)
_disallow_keyword(:axis, attributes)
return ax
end
function create_axis_like(plot::AbstractPlot, attributes::Dict, gp::GridPosition)
_disallow_keyword(:figure, attributes)
figure = get_top_parent(gp)
c = contents(gp; exact=true)
if !isempty(c)
error("""
You have used the non-mutating plotting syntax with a GridPosition, which requires an empty GridLayout slot to create an axis in, but there are already the following objects at this layout position:
$(c)
If you meant to plot into an axis at this position, use the plotting function with `!` (e.g. `func!` instead of `func`).
If you really want to place an axis on top of other blocks, make your intention clear and create it manually.
""")
end
ax = create_axis_for_plot(figure, plot, attributes)
if isnothing(ax) # For FigureSpec
return gp
else
gp[] = ax
return ax
end
end
function MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, gsp::GridSubposition)
_disallow_keyword(:figure, attributes)
layout = GridLayoutBase.get_layout_at!(gsp.parent; createmissing=false)
gp = layout[gsp.rows, gsp.cols, gsp.side]
c = contents(gp; exact=true)
if !(length(c) == 1 && can_be_current_axis(c[1]))
error("There is not just one axis at $(gp).")
end
_disallow_keyword(:axis, attributes)
return first(c)
end
function create_axis_like(plot::AbstractPlot, attributes::Dict, gsp::GridSubposition)
_disallow_keyword(:figure, attributes)
GridLayoutBase.get_layout_at!(gsp.parent; createmissing=true)
c = contents(gsp; exact=true)
if !isempty(c)
error("""
You have used the non-mutating plotting syntax with a GridSubposition, which requires an empty GridLayout slot to create an axis in, but there are already the following objects at this layout position:
$(c)
If you meant to plot into an axis at this position, use the plotting function with `!` (e.g. `func!` instead of `func`).
If you really want to place an axis on top of other blocks, make your intention clear and create it manually.
""")
end
figure = get_top_parent(gsp)
ax = create_axis_for_plot(figure, plot, attributes)
gsp.parent[gsp.rows, gsp.cols, gsp.side] = ax
return ax
end
function create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, ax::AbstractAxis)
_disallow_keyword(:axis, attributes)
return ax
end
function create_axis_like(@nospecialize(::AbstractPlot), ::Dict, ::Union{Scene,AbstractAxis})
return error("Plotting into an axis without !")
end
figurelike_return(fa::FigureAxis, plot::AbstractPlot) = FigureAxisPlot(fa.figure, fa.axis, plot)
figurelike_return(ax::AbstractAxis, plot::AbstractPlot) = AxisPlot(ax, plot)
figurelike_return!(::AbstractAxis, plot::AbstractPlot) = plot
figurelike_return!(::Union{Plot, Scene}, plot::AbstractPlot) = plot
update_state_before_display!(f::FigureAxisPlot) = update_state_before_display!(f.figure)
function update_state_before_display!(f::Figure)
for c in f.content
update_state_before_display!(c)
end
return
end
@inline plot_args(args...) = (nothing, args)
@inline function plot_args(a::Union{Figure,AbstractAxis,Scene,Plot,GridSubposition,GridPosition},
args...)
return (a, args)
end
function fig_keywords!(kws)
figkws = Dict{Symbol,Any}()
if haskey(kws, :axis)
figkws[:axis] = pop!(kws, :axis)
end
if haskey(kws, :figure)
figkws[:figure] = pop!(kws, :figure)
end
return figkws
end
# Narrows down the default plotfunc early on, if `plot` is used
default_plot_func(f::F, args) where {F} = f
default_plot_func(::typeof(plot), args) = plotfunc(plottype(map(to_value, args)...))
# Don't inline these, since they will get called from `scatter!(args...; kw...)` which gets specialized to all kw args
@noinline function MakieCore._create_plot(F, attributes::Dict, args...)
figarg, pargs = plot_args(args...)
figkws = fig_keywords!(attributes)
plot = Plot{default_plot_func(F, pargs)}(pargs, attributes)
ax = create_axis_like(plot, figkws, figarg)
plot!(ax, plot)
return figurelike_return(ax, plot)
end
@noinline function MakieCore._create_plot!(F, attributes::Dict, args...)
figarg, pargs = plot_args(args...)
figkws = fig_keywords!(attributes)
plot = Plot{default_plot_func(F, pargs)}(pargs, attributes)
ax = create_axis_like!(plot, figkws, figarg)
plot!(ax, plot)
return figurelike_return!(ax, plot)
end
@noinline function MakieCore._create_plot!(F, attributes::Dict, scene::SceneLike, args...)
plot = Plot{default_plot_func(F, args)}(args, attributes)
plot!(scene, plot)
return plot
end
# This enables convert_arguments(::Type{<:AbstractPlot}, ::X) -> FigureSpec
# Which skips axis creation
# TODO, what to return for the dynamically created axes?
const PlotSpecPlot = Plot{plot, Tuple{<: GridLayoutSpec}}
figurelike_return(f::GridPosition, p::PlotSpecPlot) = p
figurelike_return(f::Figure, p::PlotSpecPlot) = FigureAxisPlot(f, nothing, p)
MakieCore.create_axis_like!(::PlotSpecPlot, attributes::Dict, fig::Figure) = fig
MakieCore.create_axis_like!(::AbstractPlot, attributes::Dict, fig::Figure) = nothing
# Axis interface
Makie.can_be_current_axis(ax::AbstractAxis) = true
function update_state_before_display!(ax::AbstractAxis)
reset_limits!(ax)
return
end
plot!(fa::FigureAxis, plot) = plot!(fa.axis, plot)
function plot!(ax::AbstractAxis, plot::AbstractPlot)
plot!(ax.scene, plot)
# some area-like plots basically always look better if they cover the whole plot area.
# adjust the limit margins in those cases automatically.
needs_tight_limits(plot) && tightlimits!(ax)
if is_open_or_any_parent(ax.scene)
reset_limits!(ax)
end
return plot
end
function Base.delete!(ax::AbstractAxis, plot::AbstractPlot)
delete!(ax.scene, plot)
return ax
end
function Base.empty!(ax::AbstractAxis)
while !isempty(ax.scene.plots)
delete!(ax, ax.scene.plots[end])
end
return ax
end