diff --git a/.gitignore b/.gitignore index 69fe281c..8b7142dd 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ examples/.ipynb_checkpoints/* examples/meetup/.ipynb_checkpoints/* deps/plotly-latest.min.js deps/build.log +deps/deps.jl diff --git a/NEWS.md b/NEWS.md index c559c05f..15d2aaa2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -10,7 +10,43 @@ --- ## (current master) -- All new development should target Julia 1.x! + +## 0.22.1 +- push PlotsDisplay just after REPLDisplay + +## 0.22.0 +- deprecate GLVisualize +- allow 1-row and 1-column heatmaps +- add portfoliodecomposition recipe from PlotRecipes +- solve Shape bug +- simplify PyPlot backend installation +- fix wireframe bug in PyPlot +- fix color bug in PyPlot +- minor bug fixes in gr and pyplot + +## 0.21.0 +- Compatibility with StaticArrays 0.9.0 +- Up GR min version to 0.35 +- fix :mirror + +## 0.20.6 +- fixes for PlotDocs.jl +- fix gr axis color argument +- Shapes for inspectdr +- don't load plotly js file by default + +## 0.20.5 +- fix precompilation issue when depending on Plots + +## 0.20.4 +- honour `html_output_format` in Juno + +## 0.20.3 +- implement guide position in gr, pyplot and pgfplots +- inspectdr fixes +- default appveyor +- rudimentary missings support +- deprecation fixes for PGFPlots ## 0.20.0 Many updates, min julia 1.0 diff --git a/REQUIRE b/REQUIRE index a2a2f67f..aae86c2c 100644 --- a/REQUIRE +++ b/REQUIRE @@ -13,4 +13,4 @@ JSON NaNMath Requires Contour -GR 0.34.0 +GR 0.35.0 diff --git a/appveyor.yml b/appveyor.yml index d2c44998..3490f07b 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,6 +1,6 @@ environment: matrix: - - julia_version: 0.7 + # - julia_version: 0.7 - julia_version: 1 - julia_version: nightly diff --git a/deps/build.jl b/deps/build.jl index ad328049..a8cf81ff 100644 --- a/deps/build.jl +++ b/deps/build.jl @@ -1,8 +1,18 @@ #TODO: download https://cdn.plot.ly/plotly-latest.min.js to deps/ if it doesn't exist - -local_fn = joinpath(dirname(@__FILE__), "plotly-latest.min.js") -if !isfile(local_fn) - @info("Cannot find deps/plotly-latest.min.js... downloading latest version.") - download("https://cdn.plot.ly/plotly-latest.min.js", local_fn) +file_path = "" +if get(ENV, "PLOTS_HOST_DEPENDENCY_LOCAL", "false") == "true" + global file_path + local_fn = joinpath(dirname(@__FILE__), "plotly-latest.min.js") + if !isfile(local_fn) + @info("Cannot find deps/plotly-latest.min.js... downloading latest version.") + download("https://cdn.plot.ly/plotly-latest.min.js", local_fn) + isfile(local_fn) && (file_path = local_fn) + else + file_path = local_fn + end +end + +open("deps.jl", "w") do io + println(io, "const plotly_local_file_path = $(repr(file_path))") end diff --git a/src/Plots.jl b/src/Plots.jl index f6e4b19f..0a6522d6 100644 --- a/src/Plots.jl +++ b/src/Plots.jl @@ -1,9 +1,10 @@ module Plots +_current_plots_version = v"0.20.6" + using Reexport import StaticArrays -using StaticArrays.FixedSizeArrays using Dates, Printf, Statistics, Base64, LinearAlgebra import SparseArrays: findnz @@ -18,6 +19,17 @@ import JSON using Requires +if isfile(joinpath(@__DIR__, "..", "deps", "deps.jl")) + include(joinpath(@__DIR__, "..", "deps", "deps.jl")) +else + # This is a bit dirty, but I don't really see why anyone should be forced + # to build Plots, while it will just include exactly the below line + # as long as `ENV["PLOTS_HOST_DEPENDENCY_LOCAL"] = "true"` is not set. + # If the above env is set + `plotly_local_file_path == ""``, + # it will warn in the __init__ function to run build + const plotly_local_file_path = "" +end + export grid, bbox, @@ -170,6 +182,10 @@ include("backends.jl") include("output.jl") include("init.jl") +include("backends/plotly.jl") +include("backends/gr.jl") +include("backends/web.jl") + # --------------------------------------------------------- @shorthands scatter diff --git a/src/arg_desc.jl b/src/arg_desc.jl index 45dcaaa5..64ce5b93 100644 --- a/src/arg_desc.jl +++ b/src/arg_desc.jl @@ -117,7 +117,7 @@ const _arg_desc = KW( :scale => "Symbol. Scale of the axis: `:none`, `:ln`, `:log2`, `:log10`", :rotation => "Number. Degrees rotation of tick labels.", :flip => "Bool. Should we flip (reverse) the axis?", -:formatter => "Function, :scientific, or :auto. A method which converts a number to a string for tick labeling.", +:formatter => "Function, :scientific, :plain or :auto. A method which converts a number to a string for tick labeling.", :tickfontfamily => "String or Symbol. Font family of tick labels.", :tickfontsize => "Integer. Font pointsize of tick labels.", :tickfonthalign => "Symbol. Font horizontal alignment of tick labels: :hcenter, :left, :right or :center", diff --git a/src/backends.jl b/src/backends.jl index 6a5dea31..eae321f8 100644 --- a/src/backends.jl +++ b/src/backends.jl @@ -149,7 +149,7 @@ function pickDefaultBackend() @warn("You have set `PLOTS_DEFAULT_BACKEND=$env_default` but `$(backend_package_name(sym))` is not loaded.") end else - @warn("You have set PLOTS_DEFAULT_BACKEND=$env_default but it is not a valid backend package. Choose from:\n\t", + @warn("You have set PLOTS_DEFAULT_BACKEND=$env_default but it is not a valid backend package. Choose from:\n\t" * join(sort(_backends), "\n\t")) end end @@ -157,7 +157,7 @@ function pickDefaultBackend() # the ordering/inclusion of this package list is my semi-arbitrary guess at # which one someone will want to use if they have the package installed...accounting for # features, speed, and robustness - # for pkgstr in ("GR", "PyPlot", "PlotlyJS", "PGFPlots", "UnicodePlots", "InspectDR", "GLVisualize") + # for pkgstr in ("GR", "PyPlot", "PlotlyJS", "PGFPlots", "UnicodePlots", "InspectDR") # if pkgstr in keys(Pkg.installed()) # return backend(Symbol(lowercase(pkgstr))) # end @@ -213,11 +213,11 @@ function backend(sym::Symbol) backend() end -const _deprecated_backends = [:qwt, :winston, :bokeh, :gadfly, :immerse] +const _deprecated_backends = [:qwt, :winston, :bokeh, :gadfly, :immerse, :glvisualize] function warn_on_deprecated_backend(bsym::Symbol) if bsym in _deprecated_backends - @warn("Backend $bsym has been deprecated. It may not work as originally intended.") + @warn("Backend $bsym has been deprecated.") end end @@ -268,17 +268,11 @@ end -# @init_backend Immerse -# @init_backend Gadfly @init_backend PyPlot -# @init_backend Qwt @init_backend UnicodePlots -# @init_backend Winston -# @init_backend Bokeh @init_backend Plotly @init_backend PlotlyJS @init_backend GR -@init_backend GLVisualize @init_backend PGFPlots @init_backend InspectDR @init_backend HDF5 @@ -331,34 +325,127 @@ function add_backend_string(pkg::AbstractBackend) end # ------------------------------------------------------------------------------ -# glvisualize +# gr -function _initialize_backend(::GLVisualizeBackend; kw...) - @eval Main begin - import GLVisualize, GeometryTypes, Reactive, GLAbstraction, GLWindow, Contour - import GeometryTypes: Point2f0, Point3f0, Vec2f0, Vec3f0, GLNormalMesh, SimpleRectangle, Point, Vec - import FileIO, Images - export GLVisualize - import Reactive: Signal - import GLAbstraction: Style - import GLVisualize: visualize - import Plots.GL - import UnicodeFun - end +const _gr_attr = merge_with_base_supported([ + :annotations, + :background_color_legend, :background_color_inside, :background_color_outside, + :foreground_color_legend, :foreground_color_grid, :foreground_color_axis, + :foreground_color_text, :foreground_color_border, + :label, + :seriescolor, :seriesalpha, + :linecolor, :linestyle, :linewidth, :linealpha, + :markershape, :markercolor, :markersize, :markeralpha, + :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, + :fillrange, :fillcolor, :fillalpha, + :bins, + :layout, + :title, :window_title, + :guide, :lims, :ticks, :scale, :flip, + :match_dimensions, + :titlefontfamily, :titlefontsize, :titlefonthalign, :titlefontvalign, + :titlefontrotation, :titlefontcolor, + :legendfontfamily, :legendfontsize, :legendfonthalign, :legendfontvalign, + :legendfontrotation, :legendfontcolor, + :tickfontfamily, :tickfontsize, :tickfonthalign, :tickfontvalign, + :tickfontrotation, :tickfontcolor, + :guidefontfamily, :guidefontsize, :guidefonthalign, :guidefontvalign, + :guidefontrotation, :guidefontcolor, + :grid, :gridalpha, :gridstyle, :gridlinewidth, + :legend, :legendtitle, :colorbar, :colorbar_title, + :fill_z, :line_z, :marker_z, :levels, + :ribbon, :quiver, + :orientation, + :overwrite_figure, + :polar, + :aspect_ratio, + :normalize, :weights, + :inset_subplots, + :bar_width, + :arrow, + :framestyle, + :tick_direction, + :camera, + :contour_labels, +]) +const _gr_seriestype = [ + :path, :scatter, :straightline, + :heatmap, :pie, :image, + :contour, :path3d, :scatter3d, :surface, :wireframe, + :shape +] +const _gr_style = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot] +const _gr_marker = _allMarkers +const _gr_scale = [:identity, :log10] +is_marker_supported(::GRBackend, shape::Shape) = true + +function add_backend_string(::GRBackend) + """ + Pkg.add("GR") + Pkg.build("GR") + """ end # ------------------------------------------------------------------------------ -# hdf5 +# plotly -function _initialize_backend(::HDF5Backend) - @eval Main begin - import HDF5 - export HDF5 - end -end +const _plotly_attr = merge_with_base_supported([ + :annotations, + :background_color_legend, :background_color_inside, :background_color_outside, + :foreground_color_legend, :foreground_color_guide, + :foreground_color_grid, :foreground_color_axis, + :foreground_color_text, :foreground_color_border, + :foreground_color_title, + :label, + :seriescolor, :seriesalpha, + :linecolor, :linestyle, :linewidth, :linealpha, + :markershape, :markercolor, :markersize, :markeralpha, + :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, :markerstrokestyle, + :fillrange, :fillcolor, :fillalpha, + :bins, + :title, :title_location, + :titlefontfamily, :titlefontsize, :titlefonthalign, :titlefontvalign, + :titlefontcolor, + :legendfontfamily, :legendfontsize, :legendfontcolor, + :tickfontfamily, :tickfontsize, :tickfontcolor, + :guidefontfamily, :guidefontsize, :guidefontcolor, + :window_title, + :guide, :lims, :ticks, :scale, :flip, :rotation, + :tickfont, :guidefont, :legendfont, + :grid, :gridalpha, :gridlinewidth, + :legend, :colorbar, :colorbar_title, + :marker_z, :fill_z, :line_z, :levels, + :ribbon, :quiver, + :orientation, + # :overwrite_figure, + :polar, + :normalize, :weights, + # :contours, + :aspect_ratio, + :hover, + :inset_subplots, + :bar_width, + :clims, + :framestyle, + :tick_direction, + :camera, + :contour_labels, + ]) + +const _plotly_seriestype = [ + :path, :scatter, :pie, :heatmap, + :contour, :surface, :wireframe, :path3d, :scatter3d, :shape, :scattergl, + :straightline +] +const _plotly_style = [:auto, :solid, :dash, :dot, :dashdot] +const _plotly_marker = [ + :none, :auto, :circle, :rect, :diamond, :utriangle, :dtriangle, + :cross, :xcross, :pentagon, :hexagon, :octagon, :vline, :hline +] +const _plotly_scale = [:identity, :log10] # ------------------------------------------------------------------------------ -# PGFPLOTS +# pgfplots function add_backend_string(::PGFPlotsBackend) """ @@ -368,26 +455,78 @@ function add_backend_string(::PGFPlotsBackend) """ end +const _pgfplots_attr = merge_with_base_supported([ + :annotations, + :background_color_legend, + :background_color_inside, + # :background_color_outside, + # :foreground_color_legend, + :foreground_color_grid, :foreground_color_axis, + :foreground_color_text, :foreground_color_border, + :label, + :seriescolor, :seriesalpha, + :linecolor, :linestyle, :linewidth, :linealpha, + :markershape, :markercolor, :markersize, :markeralpha, + :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, :markerstrokestyle, + :fillrange, :fillcolor, :fillalpha, + :bins, + # :bar_width, :bar_edges, + :title, + # :window_title, + :guide, :guide_position, :lims, :ticks, :scale, :flip, :rotation, + :tickfont, :guidefont, :legendfont, + :grid, :legend, + :colorbar, :colorbar_title, + :fill_z, :line_z, :marker_z, :levels, + # :ribbon, :quiver, :arrow, + # :orientation, + # :overwrite_figure, + :polar, + # :normalize, :weights, :contours, + :aspect_ratio, + # :match_dimensions, + :tick_direction, + :framestyle, + :camera, + :contour_labels, +]) +const _pgfplots_seriestype = [:path, :path3d, :scatter, :steppre, :stepmid, :steppost, :histogram2d, :ysticks, :xsticks, :contour, :shape, :straightline,] +const _pgfplots_style = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot] +const _pgfplots_marker = [:none, :auto, :circle, :rect, :diamond, :utriangle, :dtriangle, :cross, :xcross, :star5, :pentagon, :hline] #vcat(_allMarkers, Shape) +const _pgfplots_scale = [:identity, :ln, :log2, :log10] + # ------------------------------------------------------------------------------ # plotlyjs +function _initialize_backend(pkg::PlotlyJSBackend) + sym = backend_package_name(pkg) + @eval Main begin + import PlotlyJS, ORCA + export PlotlyJS + end +end + function add_backend_string(::PlotlyJSBackend) """ using Pkg - Pkg.add("PlotlyJS") - Pkg.add("Rsvg") + Pkg.add(["PlotlyJS", "Blink", "ORCA"]) import Blink Blink.AtomShell.install() """ end +const _plotlyjs_attr = _plotly_attr +const _plotlyjs_seriestype = _plotly_seriestype +const _plotlyjs_style = _plotly_style +const _plotlyjs_marker = _plotly_marker +const _plotlyjs_scale = _plotly_scale + # ------------------------------------------------------------------------------ # pyplot function _initialize_backend(::PyPlotBackend) @eval Main begin - import PyPlot, PyCall - import LaTeXStrings + import PyPlot export PyPlot @@ -399,18 +538,66 @@ end function add_backend_string(::PyPlotBackend) """ using Pkg - Pkg.add("PyPlot") - Pkg.add("PyCall") - Pkg.add("LaTeXStrings") withenv("PYTHON" => "") do - Pkg.build("PyCall") + Pkg.add("PyPlot") Pkg.build("PyPlot") end """ end +const _pyplot_attr = merge_with_base_supported([ + :annotations, + :background_color_legend, :background_color_inside, :background_color_outside, + :foreground_color_grid, :foreground_color_legend, :foreground_color_title, + :foreground_color_axis, :foreground_color_border, :foreground_color_guide, :foreground_color_text, + :label, + :linecolor, :linestyle, :linewidth, :linealpha, + :markershape, :markercolor, :markersize, :markeralpha, + :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, + :fillrange, :fillcolor, :fillalpha, + :bins, :bar_width, :bar_edges, :bar_position, + :title, :title_location, :titlefont, + :window_title, + :guide, :guide_position, :lims, :ticks, :scale, :flip, :rotation, + :titlefontfamily, :titlefontsize, :titlefontcolor, + :legendfontfamily, :legendfontsize, :legendfontcolor, + :tickfontfamily, :tickfontsize, :tickfontcolor, + :guidefontfamily, :guidefontsize, :guidefontcolor, + :grid, :gridalpha, :gridstyle, :gridlinewidth, + :legend, :legendtitle, :colorbar, + :marker_z, :line_z, :fill_z, + :levels, + :ribbon, :quiver, :arrow, + :orientation, + :overwrite_figure, + :polar, + :normalize, :weights, + :contours, :aspect_ratio, + :match_dimensions, + :clims, + :inset_subplots, + :dpi, + :colorbar_title, + :stride, + :framestyle, + :tick_direction, + :camera, + :contour_labels, + ]) +const _pyplot_seriestype = [ + :path, :steppre, :steppost, :shape, :straightline, + :scatter, :hexbin, #:histogram2d, :histogram, + # :bar, + :heatmap, :pie, :image, + :contour, :contour3d, :path3d, :scatter3d, :surface, :wireframe + ] +const _pyplot_style = [:auto, :solid, :dash, :dot, :dashdot] +const _pyplot_marker = vcat(_allMarkers, :pixel) +const _pyplot_scale = [:identity, :ln, :log2, :log10] + # ------------------------------------------------------------------------------ # unicodeplots + function add_backend_string(::UnicodePlotsBackend) """ using Pkg @@ -418,3 +605,126 @@ function add_backend_string(::UnicodePlotsBackend) Pkg.build("UnicodePlots") """ end + +const _unicodeplots_attr = merge_with_base_supported([ + :label, + :legend, + :seriescolor, + :seriesalpha, + :linestyle, + :markershape, + :bins, + :title, + :guide, :lims, + ]) +const _unicodeplots_seriestype = [ + :path, :scatter, :straightline, + # :bar, + :shape, + :histogram2d, + :spy +] +const _unicodeplots_style = [:auto, :solid] +const _unicodeplots_marker = [:none, :auto, :circle] +const _unicodeplots_scale = [:identity] + +# ------------------------------------------------------------------------------ +# hdf5 + +const _hdf5_attr = merge_with_base_supported([ + :annotations, + :background_color_legend, :background_color_inside, :background_color_outside, + :foreground_color_grid, :foreground_color_legend, :foreground_color_title, + :foreground_color_axis, :foreground_color_border, :foreground_color_guide, :foreground_color_text, + :label, + :linecolor, :linestyle, :linewidth, :linealpha, + :markershape, :markercolor, :markersize, :markeralpha, + :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, + :fillrange, :fillcolor, :fillalpha, + :bins, :bar_width, :bar_edges, :bar_position, + :title, :title_location, :titlefont, + :window_title, + :guide, :lims, :ticks, :scale, :flip, :rotation, + :tickfont, :guidefont, :legendfont, + :grid, :legend, :colorbar, + :marker_z, :line_z, :fill_z, + :levels, + :ribbon, :quiver, :arrow, + :orientation, + :overwrite_figure, + :polar, + :normalize, :weights, + :contours, :aspect_ratio, + :match_dimensions, + :clims, + :inset_subplots, + :dpi, + :colorbar_title, + ]) +const _hdf5_seriestype = [ + :path, :steppre, :steppost, :shape, :straightline, + :scatter, :hexbin, #:histogram2d, :histogram, + # :bar, + :heatmap, :pie, :image, + :contour, :contour3d, :path3d, :scatter3d, :surface, :wireframe + ] +const _hdf5_style = [:auto, :solid, :dash, :dot, :dashdot] +const _hdf5_marker = vcat(_allMarkers, :pixel) +const _hdf5_scale = [:identity, :ln, :log2, :log10] + +# ------------------------------------------------------------------------------ +# inspectdr + +const _inspectdr_attr = merge_with_base_supported([ + :annotations, + :background_color_legend, :background_color_inside, :background_color_outside, + # :foreground_color_grid, + :foreground_color_legend, :foreground_color_title, + :foreground_color_axis, :foreground_color_border, :foreground_color_guide, :foreground_color_text, + :label, + :seriescolor, :seriesalpha, + :linecolor, :linestyle, :linewidth, :linealpha, + :markershape, :markercolor, :markersize, :markeralpha, + :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, + :markerstrokestyle, #Causes warning not to have it... what is this? + :fillcolor, :fillalpha, #:fillrange, +# :bins, :bar_width, :bar_edges, :bar_position, + :title, :title_location, + :window_title, + :guide, :lims, :scale, #:ticks, :flip, :rotation, + :titlefontfamily, :titlefontsize, :titlefontcolor, + :legendfontfamily, :legendfontsize, :legendfontcolor, + :tickfontfamily, :tickfontsize, :tickfontcolor, + :guidefontfamily, :guidefontsize, :guidefontcolor, + :grid, :legend, #:colorbar, +# :marker_z, +# :line_z, +# :levels, + # :ribbon, :quiver, :arrow, +# :orientation, + :overwrite_figure, + :polar, +# :normalize, :weights, +# :contours, :aspect_ratio, + :match_dimensions, +# :clims, +# :inset_subplots, + :dpi, +# :colorbar_title, + ]) +const _inspectdr_style = [:auto, :solid, :dash, :dot, :dashdot] +const _inspectdr_seriestype = [ + :path, :scatter, :shape, :straightline, #, :steppre, :steppost + ] +#see: _allMarkers, _shape_keys +const _inspectdr_marker = Symbol[ + :none, :auto, + :circle, :rect, :diamond, + :cross, :xcross, + :utriangle, :dtriangle, :rtriangle, :ltriangle, + :pentagon, :hexagon, :heptagon, :octagon, + :star4, :star5, :star6, :star7, :star8, + :vline, :hline, :+, :x, +] + +const _inspectdr_scale = [:identity, :ln, :log2, :log10] diff --git a/src/backends/glvisualize.jl b/src/backends/glvisualize.jl deleted file mode 100644 index 72288380..00000000 --- a/src/backends/glvisualize.jl +++ /dev/null @@ -1,1518 +0,0 @@ -#= -TODO - * move all gl_ methods to GLPlot - * integrate GLPlot UI - * clean up corner cases - * find a cleaner way for extracting properties - * polar plots - * labes and axis - * fix units in all visuals (e.g dotted lines, marker scale, surfaces) -=# - -const _glvisualize_attr = merge_with_base_supported([ - :annotations, - :background_color_legend, :background_color_inside, :background_color_outside, - :foreground_color_grid, :foreground_color_legend, :foreground_color_title, - :foreground_color_axis, :foreground_color_border, :foreground_color_guide, :foreground_color_text, - :label, - :linecolor, :linestyle, :linewidth, :linealpha, - :markershape, :markercolor, :markersize, :markeralpha, - :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, - :fillrange, :fillcolor, :fillalpha, - :bins, :bar_width, :bar_edges, :bar_position, - :title, :title_location, - :window_title, - :guide, :lims, :ticks, :scale, :flip, :rotation, - :titlefontsize, :titlefontcolor, - :legendfontsize, :legendfontcolor, - :tickfontsize, - :guidefontsize, :guidefontcolor, - :grid, :gridalpha, :gridstyle, :gridlinewidth, - :legend, :colorbar, - :marker_z, - :line_z, - :levels, - :ribbon, :quiver, :arrow, - :orientation, - :overwrite_figure, - #:polar, - :normalize, :weights, - :contours, :aspect_ratio, - :match_dimensions, - :clims, - :inset_subplots, - :dpi, - :hover, - :framestyle, - :tick_direction, -]) -const _glvisualize_seriestype = [ - :path, :shape, :straightline, - :scatter, :hexbin, - :bar, :boxplot, - :heatmap, :image, :volume, - :contour, :contour3d, :path3d, :scatter3d, :surface, :wireframe -] -const _glvisualize_style = [:auto, :solid, :dash, :dot, :dashdot] -const _glvisualize_marker = _allMarkers -const _glvisualize_scale = [:identity, :ln, :log2, :log10] - -slice_arg(img::Matrix{C}, idx::Int) where {C<:Colorant} = img -is_marker_supported(::GLVisualizeBackend, shape::GLVisualize.AllPrimitives) = true -is_marker_supported(::GLVisualizeBackend, shape::Union{Vector{Matrix{C}}, Matrix{C}}) where {C<:Colorant} = true -is_marker_supported(::GLVisualizeBackend, shape::Shape) = true -GL = Plots - -# --------------------------------------------------------------------------- - -# initialize the figure/window -# function _create_backend_figure(plt::Plot{GLVisualizeBackend}) -# # init a screen -# -# GLPlot.init() -# end -const _glplot_deletes = [] - - -function get_plot_screen(list::Vector, name, result = []) - for elem in list - get_plot_screen(elem, name, result) - end - return result -end -function get_plot_screen(screen, name, result = []) - if screen.name == name - push!(result, screen) - return result - end - get_plot_screen(screen.children, name, result) -end - -function create_window(plt::Plot{GLVisualizeBackend}, visible) - name = Symbol("__Plots.jl") - # make sure we have any screen open - if isempty(GLVisualize.get_screens()) - # create a fresh, new screen - parent_screen = GLVisualize.glscreen( - "Plots", - resolution = plt[:size], - visible = visible - ) - @async GLWindow.renderloop(parent_screen) - GLVisualize.add_screen(parent_screen) - end - # now lets get ourselves a permanent Plotting screen - plot_screens = get_plot_screen(GLVisualize.current_screen(), name) - screen = if isempty(plot_screens) # no screen with `name` - parent = GLVisualize.current_screen() - screen = GLWindow.Screen( - parent, area = map(GLWindow.zeroposition, parent.area), - name = name - ) - screen - elseif length(plot_screens) == 1 - plot_screens[1] - else - # okay this is silly! Lets see if we can. There is an ID we could use - # will not be fine for more than 255 screens though -.-. - error("multiple Plot screens. Please don't use any screen with the name $name") - end - # Since we own this window, we can do deep cleansing - empty!(screen) - plt.o = screen - GLWindow.set_visibility!(screen, visible) - resize!(screen, plt[:size]...) - screen -end -# --------------------------------------------------------------------------- - -const _gl_marker_map = KW( - :rect => '■', - :star5 => '★', - :diamond => '◆', - :hexagon => '⬢', - :cross => '✚', - :xcross => '❌', - :utriangle => '▲', - :dtriangle => '▼', - :ltriangle => '◀', - :rtriangle => '▶', - :pentagon => '⬟', - :octagon => '⯄', - :star4 => '✦', - :star6 => '🟋', - :star8 => '✷', - :vline => '┃', - :hline => '━', - :+ => '+', - :x => 'x', - :circle => '●' -) - -function gl_marker(shape) - shape -end -function gl_marker(shape::Shape) - points = Point2f0[GeometryTypes.Vec{2, Float32}(p) for p in zip(shape.x, shape.y)] - bb = GeometryTypes.AABB(points) - mini, maxi = minimum(bb), maximum(bb) - w3 = maxi-mini - origin, width = Point2f0(mini[1], mini[2]), Point2f0(w3[1], w3[2]) - map!(p -> ((p - origin) ./ width) - 0.5f0, points, points) # normalize and center - GeometryTypes.GLNormalMesh(points) -end -# create a marker/shape type -function gl_marker(shape::Vector{Symbol}) - String(map(shape) do sym - get(_gl_marker_map, sym, '●') - end) -end - -function gl_marker(shape::Symbol) - if shape == :rect - GeometryTypes.HyperRectangle(Vec2f0(0), Vec2f0(1)) - elseif shape == :circle || shape == :none - GeometryTypes.HyperSphere(Point2f0(0), 1f0) - elseif haskey(_gl_marker_map, shape) - _gl_marker_map[shape] - elseif haskey(_shapes, shape) - gl_marker(_shapes[shape]) - else - error("Shape $shape not supported by GLVisualize") - end -end - -function extract_limits(sp, plotattributes, kw_args) - clims = sp[:clims] - if is_2tuple(clims) - if isfinite(clims[1]) && isfinite(clims[2]) - kw_args[:limits] = Vec2f0(clims) - end - end - nothing -end - -to_vec(::Type{T}, vec::T) where {T <: StaticArrays.StaticVector} = vec -to_vec(::Type{T}, s::Number) where {T <: StaticArrays.StaticVector} = T(s) - -to_vec(::Type{T}, vec::StaticArrays.StaticVector{3}) where {T <: StaticArrays.StaticVector{2}} = T(vec[1], vec[2]) -to_vec(::Type{T}, vec::StaticArrays.StaticVector{2}) where {T <: StaticArrays.StaticVector{3}} = T(vec[1], vec[2], 0) - -to_vec(::Type{T}, vecs::AbstractVector) where {T <: StaticArrays.StaticVector} = map(x-> to_vec(T, x), vecs) - -function extract_marker(plotattributes, kw_args) - dim = Plots.is3d(plotattributes) ? 3 : 2 - scaling = dim == 3 ? 0.003 : 2 - if haskey(plotattributes, :markershape) - shape = plotattributes[:markershape] - shape = gl_marker(shape) - if shape != :none - kw_args[:primitive] = shape - end - end - dim = isa(kw_args[:primitive], GLVisualize.Sprites) ? 2 : 3 - if haskey(plotattributes, :markersize) - msize = plotattributes[:markersize] - kw_args[:scale] = to_vec(GeometryTypes.Vec{dim, Float32}, msize .* scaling) - end - if haskey(plotattributes, :offset) - kw_args[:offset] = plotattributes[:offset] - end - # get the color - key = :markercolor - haskey(plotattributes, key) || return - c = gl_color(plotattributes[key]) - if isa(c, AbstractVector) && plotattributes[:marker_z] != nothing - extract_colornorm(plotattributes, kw_args) - kw_args[:color] = nothing - kw_args[:color_map] = c - kw_args[:intensity] = convert(Vector{Float32}, plotattributes[:marker_z]) - else - kw_args[:color] = c - end - key = :markerstrokecolor - haskey(plotattributes, key) || return - c = gl_color(plotattributes[key]) - if c != nothing - if !(isa(c, Colorant) || (isa(c, Vector) && eltype(c) <: Colorant)) - error("Stroke Color not supported: $c") - end - kw_args[:stroke_color] = c - kw_args[:stroke_width] = Float32(plotattributes[:markerstrokewidth]) - end -end - -function _extract_surface(plotattributes::Plots.Surface) - plotattributes.surf -end -function _extract_surface(plotattributes::AbstractArray) - plotattributes -end - -# TODO when to transpose?? -function extract_surface(plotattributes) - map(_extract_surface, (plotattributes[:x], plotattributes[:y], plotattributes[:z])) -end -function topoints(::Type{P}, array) where P - [P(x) for x in zip(array...)] -end -function extract_points(plotattributes) - dim = is3d(plotattributes) ? 3 : 2 - array = if plotattributes[:seriestype] == :straightline - straightline_data(plotattributes) - elseif plotattributes[:seriestype] == :shape - shape_data(plotattributes) - else - (plotattributes[:x], plotattributes[:y], plotattributes[:z])[1:dim] - end - topoints(Point{dim, Float32}, array) -end -function make_gradient(grad::Vector{C}) where C <: Colorant - grad -end -function make_gradient(grad::ColorGradient) - RGBA{Float32}[c for c in grad.colors] -end -make_gradient(c) = make_gradient(cgrad()) - -function extract_any_color(plotattributes, kw_args) - if plotattributes[:marker_z] == nothing - c = scalar_color(plotattributes, :fill) - extract_c(plotattributes, kw_args, :fill) - if isa(c, Colorant) - kw_args[:color] = c - else - kw_args[:color] = nothing - kw_args[:color_map] = make_gradient(c) - clims = plotattributes[:subplot][:clims] - if Plots.is_2tuple(clims) - if isfinite(clims[1]) && isfinite(clims[2]) - kw_args[:color_norm] = Vec2f0(clims) - end - elseif clims == :auto - kw_args[:color_norm] = Vec2f0(ignorenan_extrema(plotattributes[:y])) - end - end - else - kw_args[:color] = nothing - clims = plotattributes[:subplot][:clims] - if Plots.is_2tuple(clims) - if isfinite(clims[1]) && isfinite(clims[2]) - kw_args[:color_norm] = Vec2f0(clims) - end - elseif clims == :auto - kw_args[:color_norm] = Vec2f0(ignorenan_extrema(plotattributes[:y])) - else - error("Unsupported limits: $clims") - end - kw_args[:intensity] = convert(Vector{Float32}, plotattributes[:marker_z]) - kw_args[:color_map] = gl_color_map(plotattributes, :marker) - end -end - -function extract_stroke(plotattributes, kw_args) - extract_c(plotattributes, kw_args, :line) - if haskey(plotattributes, :linewidth) - kw_args[:thickness] = Float32(plotattributes[:linewidth] * 3) - end -end - -function extract_color(plotattributes, sym) - plotattributes[Symbol("$(sym)color")] -end - -gl_color(c::PlotUtils.ColorGradient) = c.colors -gl_color(c::Vector{T}) where {T<:Colorant} = c -gl_color(c::RGBA{Float32}) = c -gl_color(c::Colorant) = RGBA{Float32}(c) - -function gl_color(tuple::Tuple) - gl_color(tuple...) -end - -# convert to RGBA -function gl_color(c, a) - c = convertColor(c, a) - RGBA{Float32}(c) -end -function scalar_color(plotattributes, sym) - gl_color(extract_color(plotattributes, sym)) -end - -function gl_color_map(plotattributes, sym) - colors = extract_color(plotattributes, sym) - _gl_color_map(colors) -end -function _gl_color_map(colors::PlotUtils.ColorGradient) - colors.colors -end -function _gl_color_map(c) - Plots.default_gradient() -end - - - -dist(a, b) = abs(a-b) -mindist(x, a, b) = NaNMath.min(dist(a, x), dist(b, x)) - -function gappy(x, ps) - n = length(ps) - x <= first(ps) && return first(ps) - x - for j=1:(n-1) - p0 = ps[j] - p1 = ps[NaNMath.min(j+1, n)] - if p0 <= x && p1 >= x - return mindist(x, p0, p1) * (isodd(j) ? 1 : -1) - end - end - return last(ps) - x -end -function ticks(points, resolution) - Float16[gappy(x, points) for x = range(first(points), stop=last(points), length=resolution)] -end - - -function insert_pattern!(points, kw_args) - tex = GLAbstraction.Texture(ticks(points, 100), x_repeat=:repeat) - kw_args[:pattern] = tex - kw_args[:pattern_length] = Float32(last(points)) -end -function extract_linestyle(plotattributes, kw_args) - haskey(plotattributes, :linestyle) || return - ls = plotattributes[:linestyle] - lw = plotattributes[:linewidth] - kw_args[:thickness] = Float32(lw) - if ls == :dash - points = [0.0, lw, 2lw, 3lw, 4lw] - insert_pattern!(points, kw_args) - elseif ls == :dot - tick, gap = lw/2, lw/4 - points = [0.0, tick, tick+gap, 2tick+gap, 2tick+2gap] - insert_pattern!(points, kw_args) - elseif ls == :dashdot - dtick, dgap = lw, lw - ptick, pgap = lw/2, lw/4 - points = [0.0, dtick, dtick+dgap, dtick+dgap+ptick, dtick+dgap+ptick+pgap] - insert_pattern!(points, kw_args) - elseif ls == :dashdotdot - dtick, dgap = lw, lw - ptick, pgap = lw/2, lw/4 - points = [0.0, dtick, dtick+dgap, dtick+dgap+ptick, dtick+dgap+ptick+pgap, dtick+dgap+ptick+pgap+ptick, dtick+dgap+ptick+pgap+ptick+pgap] - insert_pattern!(points, kw_args) - end - extract_c(plotattributes, kw_args, :line) - nothing -end - -function hover(to_hover::Vector, to_display, window) - hover(to_hover[], to_display, window) -end - -function get_cam(x) - if isa(x, GLAbstraction.Context) - return get_cam(x.children) - elseif isa(x, Vector) - return get_cam(first(x)) - elseif isa(x, GLAbstraction.RenderObject) - return x[:preferred_camera] - end -end - - -function hover(to_hover, to_display, window) - if isa(to_hover, GLAbstraction.Context) - return hover(to_hover.children, to_display, window) - end - area = map(window.inputs[:mouseposition]) do mp - SimpleRectangle{Int}(round(Int, mp+10)..., 100, 70) - end - mh = GLWindow.mouse2id(window) - popup = GLWindow.Screen( - window, - hidden = map(mh-> !(mh.id == to_hover.id), mh), - area = area, - stroke = (2f0, RGBA(0f0, 0f0, 0f0, 0.8f0)) - ) - cam = get!(popup.cameras, :perspective) do - GLAbstraction.PerspectiveCamera( - popup.inputs, Vec3f0(3), Vec3f0(0), - keep = Signal(false), - theta = Signal(Vec3f0(0)), trans = Signal(Vec3f0(0)) - ) - end - - map(enumerate(to_display)) do id - i,d = id - robj = visualize(d) - viewit = Reactive.droprepeats(map(mh->mh.id == to_hover.id && mh.index == i, mh)) - camtype = get_cam(robj) - Reactive.preserve(map(viewit) do vi - if vi - empty!(popup) - if camtype == :perspective - cam.projectiontype.value = GLVisualize.PERSPECTIVE - else - cam.projectiontype.value = GLVisualize.ORTHOGRAPHIC - end - GLVisualize._view(robj, popup, camera = cam) - bb = GLAbstraction.boundingbox(robj).value - mini = minimum(bb) - w = GeometryTypes.widths(bb) - wborder = w * 0.08f0 #8 percent border - bb = GeometryTypes.AABB{Float32}(mini - wborder, w + 2 * wborder) - GLAbstraction.center!(cam, bb) - end - end) - end - nothing -end - -function extract_extrema(plotattributes, kw_args) - xmin, xmax = ignorenan_extrema(plotattributes[:x]); ymin, ymax = ignorenan_extrema(plotattributes[:y]) - kw_args[:primitive] = GeometryTypes.SimpleRectangle{Float32}(xmin, ymin, xmax-xmin, ymax-ymin) - nothing -end - -function extract_font(font, kw_args) - kw_args[:family] = font.family - kw_args[:relative_scale] = pointsize(font) - kw_args[:color] = gl_color(font.color) -end - -function extract_colornorm(plotattributes, kw_args) - clims = plotattributes[:subplot][:clims] - if Plots.is_2tuple(clims) - if isfinite(clims[1]) && isfinite(clims[2]) - kw_args[:color_norm] = Vec2f0(clims) - end - elseif clims == :auto - z = if haskey(plotattributes, :marker_z) && plotattributes[:marker_z] != nothing - plotattributes[:marker_z] - elseif haskey(plotattributes, :line_z) && plotattributes[:line_z] != nothing - plotattributes[:line_z] - elseif isa(plotattributes[:z], Plots.Surface) - plotattributes[:z].surf - else - plotattributes[:y] - end - kw_args[:color_norm] = Vec2f0(ignorenan_extrema(z)) - kw_args[:intensity] = map(Float32, collect(z)) - end -end - -function extract_gradient(plotattributes, kw_args, sym) - key = Symbol("$(sym)color") - haskey(plotattributes, key) || return - c = make_gradient(plotattributes[key]) - kw_args[:color] = nothing - extract_colornorm(plotattributes, kw_args) - kw_args[:color_map] = c - return -end - -function extract_c(plotattributes, kw_args, sym) - key = Symbol("$(sym)color") - haskey(plotattributes, key) || return - c = gl_color(plotattributes[key]) - kw_args[:color] = nothing - kw_args[:color_map] = nothing - kw_args[:color_norm] = nothing - if ( - isa(c, AbstractVector) && - ((haskey(plotattributes, :marker_z) && plotattributes[:marker_z] != nothing) || - (haskey(plotattributes, :line_z) && plotattributes[:line_z] != nothing)) - ) - extract_colornorm(plotattributes, kw_args) - kw_args[:color_map] = c - else - kw_args[:color] = c - end - return -end - -function extract_stroke(plotattributes, kw_args, sym) - key = Symbol("$(sym)strokecolor") - haskey(plotattributes, key) || return - c = gl_color(plotattributes[key]) - if c != nothing - if !isa(c, Colorant) - error("Stroke Color not supported: $c") - end - kw_args[:stroke_color] = c - kw_args[:stroke_width] = Float32(plotattributes[Symbol("$(sym)strokewidth")]) * 2 - end - return -end - - - -function draw_grid_lines(sp, grid_segs, thickness, style, model, color) - - kw_args = Dict{Symbol, Any}( - :model => model - ) - plotattributes = Dict( - :linestyle => style, - :linewidth => Float32(thickness), - :linecolor => color - ) - Plots.extract_linestyle(plotattributes, kw_args) - GL.gl_lines(map(Point2f0, grid_segs.pts), kw_args) -end - -function align_offset(startpos, lastpos, atlas, rscale, font, align) - xscale, yscale = GLVisualize.glyph_scale!('X', rscale) - xmove = (lastpos-startpos)[1] + xscale - if isa(align, GeometryTypes.Vec) - return -Vec2f0(xmove, yscale) .* align - elseif align == :top - return -Vec2f0(xmove/2f0, yscale) - elseif align == :right - return -Vec2f0(xmove, yscale/2f0) - else - error("Align $align not known") - end -end - - -function alignment2num(x::Symbol) - (x in (:hcenter, :vcenter)) && return 0.5 - (x in (:left, :bottom)) && return 0.0 - (x in (:right, :top)) && return 1.0 - 0.0 # 0 default, or better to error? -end - -function alignment2num(font::Plots.Font) - Vec2f0(map(alignment2num, (font.halign, font.valign))) -end - -pointsize(font) = font.pointsize * 2 - -function draw_ticks( - axis, ticks, isx, isorigin, lims, m, text = "", - positions = Point2f0[], offsets=Vec2f0[] - ) - sz = pointsize(tickfont(axis)) - atlas = GLVisualize.get_texture_atlas() - font = GLVisualize.defaultfont() - - flip = axis[:flip]; mirror = axis[:mirror] - - align = if isx - mirror ? :bottom : :top - else - mirror ? :left : :right - end - axis_gap = Point2f0(isx ? 0 : sz / 2, isx ? sz / 2 : 0) - for (cv, dv) in zip(ticks...) - - x, y = cv, lims[1] - xy = if isorigin - isx ? (x, 0) : (0, x) - else - isx ? (x, y) : (y, x) - end - _pos = m * GeometryTypes.Vec4f0(xy[1], xy[2], 0, 1) - startpos = Point2f0(_pos[1], _pos[2]) - axis_gap - str = string(dv) - # need to tag a new UnicodeFun version for this... also the numbers become - # so small that it looks terrible -.- - # _str = split(string(dv), "^") - # if length(_str) == 2 - # _str[2] = UnicodeFun.to_superscript(_str[2]) - # end - # str = join(_str, "") - position = GLVisualize.calc_position(str, startpos, sz, font, atlas) - offset = GLVisualize.calc_offset(str, sz, font, atlas) - alignoff = align_offset(startpos, last(position), atlas, sz, font, align) - map!(position, position) do pos - pos .+ alignoff - end - append!(positions, position) - append!(offsets, offset) - text *= str - - end - text, positions, offsets -end - -function glvisualize_text(position, text, kw_args) - text_align = alignment2num(text.font) - startpos = Vec2f0(position) - atlas = GLVisualize.get_texture_atlas() - font = GLVisualize.defaultfont() - rscale = kw_args[:relative_scale] - - position = GLVisualize.calc_position(text.str, startpos, rscale, font, atlas) - offset = GLVisualize.calc_offset(text.str, rscale, font, atlas) - alignoff = align_offset(startpos, last(position), atlas, rscale, font, text_align) - - map!(position, position) do pos - pos .+ alignoff - end - kw_args[:position] = position - kw_args[:offset] = offset - kw_args[:scale_primitive] = true - visualize(text.str, Style(:default), kw_args) -end - -function text_model(font, pivot) - pv = GeometryTypes.Vec3f0(pivot[1], pivot[2], 0) - if font.rotation != 0.0 - rot = Float32(deg2rad(font.rotation)) - rotm = GLAbstraction.rotationmatrix_z(rot) - return GLAbstraction.translationmatrix(pv)*rotm*GLAbstraction.translationmatrix(-pv) - else - eye(GeometryTypes.Mat4f0) - end -end -function gl_draw_axes_2d(sp::Plots.Subplot{Plots.GLVisualizeBackend}, model, area) - xticks, yticks, xspine_segs, yspine_segs, xtick_segs, ytick_segs, xgrid_segs, ygrid_segs, xminorgrid_segs, yminorgrid_segs, xborder_segs, yborder_segs = Plots.axis_drawing_info(sp) - xaxis = sp[:xaxis]; yaxis = sp[:yaxis] - - xgc = Colors.color(Plots.gl_color(xaxis[:foreground_color_grid])) - ygc = Colors.color(Plots.gl_color(yaxis[:foreground_color_grid])) - axis_vis = [] - if xaxis[:grid] - grid = draw_grid_lines(sp, xgrid_segs, xaxis[:gridlinewidth], xaxis[:gridstyle], model, RGBA(xgc, xaxis[:gridalpha])) - push!(axis_vis, grid) - end - if yaxis[:grid] - grid = draw_grid_lines(sp, ygrid_segs, yaxis[:gridlinewidth], yaxis[:gridstyle], model, RGBA(ygc, yaxis[:gridalpha])) - push!(axis_vis, grid) - end - if xaxis[:minorgrid] - minorgrid = draw_minorgrid_lines(sp, xminorgrid_segs, xaxis[:minorgridlinewidth], xaxis[:minorgridstyle], model, RGBA(xgc, xaxis[:minorgridalpha])) - push!(axis_vis, minorgrid) - end - if yaxis[:minorgrid] - minorgrid = draw_minorgrid_lines(sp, yminorgrid_segs, yaxis[:minorgridlinewidth], yaxis[:minorgridstyle], model, RGBA(ygc, yaxis[:minorgridalpha])) - push!(axis_vis, minorgrid) - end - - xac = Colors.color(Plots.gl_color(xaxis[:foreground_color_axis])) - yac = Colors.color(Plots.gl_color(yaxis[:foreground_color_axis])) - if alpha(xaxis[:foreground_color_axis]) > 0 - spine = draw_grid_lines(sp, xspine_segs, 1f0, :solid, model, RGBA(xac, 1.0f0)) - push!(axis_vis, spine) - end - if alpha(yaxis[:foreground_color_axis]) > 0 - spine = draw_grid_lines(sp, yspine_segs, 1f0, :solid, model, RGBA(yac, 1.0f0)) - push!(axis_vis, spine) - end - if sp[:framestyle] in (:zerolines, :grid) - if alpha(xaxis[:foreground_color_grid]) > 0 - spine = draw_grid_lines(sp, xtick_segs, 1f0, :solid, model, RGBA(xgc, xaxis[:gridalpha])) - push!(axis_vis, spine) - end - if alpha(yaxis[:foreground_color_grid]) > 0 - spine = draw_grid_lines(sp, ytick_segs, 1f0, :solid, model, RGBA(ygc, yaxis[:gridalpha])) - push!(axis_vis, spine) - end - else - if alpha(xaxis[:foreground_color_axis]) > 0 - spine = draw_grid_lines(sp, xtick_segs, 1f0, :solid, model, RGBA(xac, 1.0f0)) - push!(axis_vis, spine) - end - if alpha(yaxis[:foreground_color_axis]) > 0 - spine = draw_grid_lines(sp, ytick_segs, 1f0, :solid, model, RGBA(yac, 1.0f0)) - push!(axis_vis, spine) - end - end - fcolor = Plots.gl_color(xaxis[:foreground_color_axis]) - - xlim = Plots.axis_limits(xaxis) - ylim = Plots.axis_limits(yaxis) - - if !(xaxis[:ticks] in (nothing, false, :none)) && !(sp[:framestyle] == :none) && xaxis[:showaxis] - ticklabels = map(model) do m - mirror = xaxis[:mirror] - t, positions, offsets = draw_ticks(xaxis, xticks, true, sp[:framestyle] == :origin, ylim, m) - end - kw_args = Dict{Symbol, Any}( - :position => map(x-> x[2], ticklabels), - :offset => map(last, ticklabels), - :color => fcolor, - :relative_scale => pointsize(tickfont(xaxis)), - :scale_primitive => false - ) - push!(axis_vis, visualize(map(first, ticklabels), Style(:default), kw_args)) - end - - if !(yaxis[:ticks] in (nothing, false, :none)) && !(sp[:framestyle] == :none) && yaxis[:showaxis] - ticklabels = map(model) do m - mirror = yaxis[:mirror] - t, positions, offsets = draw_ticks(yaxis, yticks, false, sp[:framestyle] == :origin, xlim, m) - end - kw_args = Dict{Symbol, Any}( - :position => map(x-> x[2], ticklabels), - :offset => map(last, ticklabels), - :color => fcolor, - :relative_scale => pointsize(tickfont(xaxis)), - :scale_primitive => false - ) - push!(axis_vis, visualize(map(first, ticklabels), Style(:default), kw_args)) - end - - xbc = Colors.color(Plots.gl_color(xaxis[:foreground_color_border])) - ybc = Colors.color(Plots.gl_color(yaxis[:foreground_color_border])) - intensity = sp[:framestyle] == :semi ? 0.5f0 : 1.0f0 - if sp[:framestyle] in (:box, :semi) - xborder = draw_grid_lines(sp, xborder_segs, intensity, :solid, model, RGBA(xbc, intensity)) - yborder = draw_grid_lines(sp, yborder_segs, intensity, :solid, model, RGBA(ybc, intensity)) - push!(axis_vis, xborder, yborder) - end - - area_w = GeometryTypes.widths(area) - if sp[:title] != "" - tf = titlefont(sp) - font = Plots.Font(tf.family, tf.pointsize, :hcenter, :top, tf.rotation, tf.color) - xy = Point2f0(area.w/2, area_w[2] + pointsize(tf)/2) - kw = Dict(:model => text_model(font, xy), :scale_primitive => true) - extract_font(font, kw) - t = PlotText(sp[:title], font) - push!(axis_vis, glvisualize_text(xy, t, kw)) - end - if xaxis[:guide] != "" - tf = guidefont(xaxis) - xy = Point2f0(area.w/2, - pointsize(tf)/2) - font = Plots.Font(tf.family, tf.pointsize, :hcenter, :bottom, tf.rotation, tf.color) - kw = Dict(:model => text_model(font, xy), :scale_primitive => true) - t = PlotText(xaxis[:guide], font) - extract_font(font, kw) - push!(axis_vis, glvisualize_text(xy, t, kw)) - end - - if yaxis[:guide] != "" - tf = guidefont(yaxis) - font = Plots.Font(tf.family, tf.pointsize, :hcenter, :top, 90f0, tf.color) - xy = Point2f0(-pointsize(tf)/2, area.h/2) - kw = Dict(:model => text_model(font, xy), :scale_primitive=>true) - t = PlotText(yaxis[:guide], font) - extract_font(font, kw) - push!(axis_vis, glvisualize_text(xy, t, kw)) - end - - axis_vis -end - -function gl_draw_axes_3d(sp, model) - x = Plots.axis_limits(sp[:xaxis]) - y = Plots.axis_limits(sp[:yaxis]) - z = Plots.axis_limits(sp[:zaxis]) - - min = Vec3f0(x[1], y[1], z[1]) - visualize( - GeometryTypes.AABB{Float32}(min, Vec3f0(x[2], y[2], z[2])-min), - :grid, model=model - ) -end - -function gl_bar(plotattributes, kw_args) - x, y = plotattributes[:x], plotattributes[:y] - nx, ny = length(x), length(y) - axis = plotattributes[:subplot][isvertical(plotattributes) ? :xaxis : :yaxis] - cv = [discrete_value!(axis, xi)[1] for xi=x] - x = if nx == ny - cv - elseif nx == ny + 1 - 0.5diff(cv) + cv[1:end-1] - else - error("bar recipe: x must be same length as y (centers), or one more than y (edges).\n\t\tlength(x)=$(length(x)), length(y)=$(length(y))") - end - if haskey(kw_args, :stroke_width) # stroke is inside for bars - #kw_args[:stroke_width] = -kw_args[:stroke_width] - end - # compute half-width of bars - bw = nothing - hw = if bw == nothing - ignorenan_mean(diff(x)) - else - Float64[_cycle(bw,i)*0.5 for i=1:length(x)] - end - - # make fillto a vector... default fills to 0 - fillto = plotattributes[:fillrange] - if fillto == nothing - fillto = 0 - end - # create the bar shapes by adding x/y segments - positions, scales = Array{Point2f0}(undef, ny), Array{Vec2f0}(undef, ny) - m = Reactive.value(kw_args[:model]) - sx, sy = m[1,1], m[2,2] - for i=1:ny - center = x[i] - hwi = abs(_cycle(hw,i)); yi = y[i]; fi = _cycle(fillto,i) - if Plots.isvertical(plotattributes) - sz = (hwi*sx, yi*sy) - else - sz = (yi*sx, hwi*2*sy) - end - positions[i] = (center-hwi*0.5, fi) - scales[i] = sz - end - - kw_args[:scale] = scales - kw_args[:offset] = Vec2f0(0) - visualize((GLVisualize.RECTANGLE, positions), Style(:default), kw_args) - #[] -end - -const _box_halfwidth = 0.4 - -notch_width(q2, q4, N) = 1.58 * (q4-q2)/sqrt(N) - -function gl_boxplot(plotattributes, kw_args) - kwbox = copy(kw_args) - range = 1.5; notch = false - x, y = plotattributes[:x], plotattributes[:y] - glabels = sort(collect(unique(x))) - warning = false - outliers_x, outliers_y = zeros(0), zeros(0) - - box_pos = Point2f0[] - box_scale = Vec2f0[] - outliers = Point2f0[] - t_segments = Point2f0[] - m = Reactive.value(kw_args[:model]) - sx, sy = m[1,1], m[2,2] - for (i,glabel) in enumerate(glabels) - # filter y - values = y[filter(i -> _cycle(x,i) == glabel, 1:length(y))] - # compute quantiles - q1,q2,q3,q4,q5 = quantile(values, range(0, stop=1, length=5)) - # notch - n = Plots.notch_width(q2, q4, length(values)) - # warn on inverted notches? - if notch && !warning && ( (q2>(q3-n)) || (q4<(q3+n)) ) - @warn("Boxplot's notch went outside hinges. Set notch to false.") - warning = true # Show the warning only one time - end - - # make the shape - center = Plots.discrete_value!(plotattributes[:subplot][:xaxis], glabel)[1] - hw = plotattributes[:bar_width] == nothing ? Plots._box_halfwidth*2 : _cycle(plotattributes[:bar_width], i) - l, m, r = center - hw/2, center, center + hw/2 - - # internal nodes for notches - L, R = center - 0.5 * hw, center + 0.5 * hw - # outliers - if Float64(range) != 0.0 # if the range is 0.0, the whiskers will extend to the data - limit = range*(q4-q2) - inside = Float64[] - for value in values - if (value < (q2 - limit)) || (value > (q4 + limit)) - push!(outliers, (center, value)) - else - push!(inside, value) - end - end - # change q1 and q5 to show outliers - # using maximum and minimum values inside the limits - q1, q5 = ignorenan_extrema(inside) - end - # Box - if notch - push!(t_segments, (m, q1), (l, q1), (r, q1), (m, q1), (m, q2))# lower T - push!(box_pos, (l, q2));push!(box_scale, (hw*sx, n*sy)) # lower box - push!(box_pos, (l, q4));push!(box_scale, (hw*sx, n*sy)) # upper box - push!(t_segments, (m, q5), (l, q5), (r, q5), (m, q5), (m, q4))# upper T - - else - push!(t_segments, (m, q2), (m, q1), (l, q1), (r, q1))# lower T - push!(box_pos, (l, q2)); push!(box_scale, (hw*sx, (q3-q2)*sy)) # lower box - push!(box_pos, (l, q4)); push!(box_scale, (hw*sx, (q3-q4)*sy)) # upper box - push!(t_segments, (m, q4), (m, q5), (r, q5), (l, q5))# upper T - end - end - kwbox = Dict{Symbol, Any}( - :scale => box_scale, - :model => kw_args[:model], - :offset => Vec2f0(0), - ) - extract_marker(plotattributes, kw_args) - outlier_kw = Dict( - :model => kw_args[:model], - :color => scalar_color(plotattributes, :fill), - :stroke_width => Float32(plotattributes[:markerstrokewidth]), - :stroke_color => scalar_color(plotattributes, :markerstroke), - ) - lines_kw = Dict( - :model => kw_args[:model], - :stroke_width => plotattributes[:linewidth], - :stroke_color => scalar_color(plotattributes, :fill), - ) - vis1 = GLVisualize.visualize((GLVisualize.RECTANGLE, box_pos), Style(:default), kwbox) - vis2 = GLVisualize.visualize((GLVisualize.CIRCLE, outliers), Style(:default), outlier_kw) - vis3 = GLVisualize.visualize(t_segments, Style(:linesegment), lines_kw) - [vis1, vis2, vis3] -end - - -# --------------------------------------------------------------------------- -function gl_viewport(bb, rect) - l, b, bw, bh = bb - rw, rh = rect.w, rect.h - GLVisualize.SimpleRectangle( - round(Int, rw * l), - round(Int, rh * b), - round(Int, rw * bw), - round(Int, rh * bh) - ) -end - -function to_modelmatrix(rect, subrect, rel_plotarea, sp) - xmin, xmax = Plots.axis_limits(sp[:xaxis]) - ymin, ymax = Plots.axis_limits(sp[:yaxis]) - mini, maxi = Vec3f0(xmin, ymin, 0), Vec3f0(xmax, ymax, 1) - if Plots.is3d(sp) - zmin, zmax = Plots.axis_limits(sp[:zaxis]) - mini, maxi = Vec3f0(xmin, ymin, zmin), Vec3f0(xmax, ymax, zmax) - s = Vec3f0(1) ./ (maxi-mini) - return GLAbstraction.scalematrix(s)*GLAbstraction.translationmatrix(-mini) - end - l, b, bw, bh = rel_plotarea - w, h = rect.w*bw, rect.h*bh - x, y = rect.w*l - subrect.x, rect.h*b - subrect.y - t = -mini - s = Vec3f0(w, h, 1) ./ (maxi-mini) - GLAbstraction.translationmatrix(Vec3f0(x,y,0))*GLAbstraction.scalematrix(s)*GLAbstraction.translationmatrix(t) -end - -# ---------------------------------------------------------------- - - -function scale_for_annotations!(series::Series, scaletype::Symbol = :pixels) - anns = series[:series_annotations] - if anns != nothing && anns.baseshape != nothing - # we use baseshape to overwrite the markershape attribute - # with a list of custom shapes for each - msw, msh = anns.scalefactor - offsets = Array{Vec2f0}(undef, length(anns.strs)) - series[:markersize] = map(1:length(anns.strs)) do i - str = _cycle(anns.strs, i) - # get the width and height of the string (in mm) - sw, sh = text_size(str, anns.font.pointsize) - - # how much to scale the base shape? - # note: it's a rough assumption that the shape fills the unit box [-1,-1,1,1], - # so we scale the length-2 shape by 1/2 the total length - xscale = 0.5to_pixels(sw) * 1.8 - yscale = 0.5to_pixels(sh) * 1.8 - - # we save the size of the larger direction to the markersize list, - # and then re-scale a copy of baseshape to match the w/h ratio - s = Vec2f0(xscale, yscale) - offsets[i] = -s - s - end - series[:offset] = offsets - end - return -end - - - - -function _display(plt::Plot{GLVisualizeBackend}, visible = true) - screen = create_window(plt, visible) - sw, sh = plt[:size] - sw, sh = sw*px, sh*px - - for sp in plt.subplots - _3d = Plots.is3d(sp) - # camera = :perspective - # initialize the sub-screen for this subplot - rel_bbox = Plots.bbox_to_pcts(bbox(sp), sw, sh) - sub_area = map(screen.area) do rect - Plots.gl_viewport(rel_bbox, rect) - end - c = plt[:background_color_outside] - sp_screen = GLVisualize.Screen( - screen, color = c, - area = sub_area - ) - sp.o = sp_screen - cam = get!(sp_screen.cameras, :perspective) do - inside = sp_screen.inputs[:mouseinside] - theta = _3d ? nothing : Signal(Vec3f0(0)) # surpress rotation for 2D (nothing will get usual rotation controle) - GLAbstraction.PerspectiveCamera( - sp_screen.inputs, Vec3f0(3), Vec3f0(0), - keep = inside, theta = theta - ) - end - - rel_plotarea = Plots.bbox_to_pcts(plotarea(sp), sw, sh) - model_m = map(Plots.to_modelmatrix, - screen.area, sub_area, - Signal(rel_plotarea), Signal(sp) - ) - - # loop over the series and add them to the subplot - if !_3d - axis = gl_draw_axes_2d(sp, model_m, Reactive.value(sub_area)) - GLVisualize._view(axis, sp_screen, camera=:perspective) - cam.projectiontype.value = GLVisualize.ORTHOGRAPHIC - Reactive.run_till_now() # make sure Reactive.push! arrives - GLAbstraction.center!(cam, - GeometryTypes.AABB( - Vec3f0(-20), Vec3f0((GeometryTypes.widths(sp_screen)+40f0)..., 1) - ) - ) - else - axis = gl_draw_axes_3d(sp, model_m) - GLVisualize._view(axis, sp_screen, camera=:perspective) - push!(cam.projectiontype, GLVisualize.PERSPECTIVE) - end - for series in Plots.series_list(sp) - - plotattributes = series.plotattributes - st = plotattributes[:seriestype]; kw_args = KW() # exctract kw - - kw_args[:model] = model_m # add transformation - if !_3d # 3D is treated differently, since we need boundingboxes for camera - kw_args[:boundingbox] = nothing # don't calculate bb, we dont need it - end - scale_for_annotations!(series) - if st in (:surface, :wireframe) - x, y, z = extract_surface(plotattributes) - extract_gradient(plotattributes, kw_args, :fill) - z = Plots.transpose_z(plotattributes, z, false) - if isa(x, AbstractMatrix) && isa(y, AbstractMatrix) - x, y = Plots.transpose_z(plotattributes, x, false), Plots.transpose_z(plotattributes, y, false) - end - if st == :wireframe - kw_args[:wireframe] = true - kw_args[:stroke_color] = plotattributes[:linecolor] - kw_args[:stroke_width] = Float32(plotattributes[:linewidth]/100f0) - end - vis = GL.gl_surface(x, y, z, kw_args) - elseif (st in (:path, :path3d, :straightline)) && plotattributes[:linewidth] > 0 - kw = copy(kw_args) - points = Plots.extract_points(plotattributes) - extract_linestyle(plotattributes, kw) - vis = GL.gl_lines(points, kw) - if plotattributes[:markershape] != :none - kw = copy(kw_args) - extract_stroke(plotattributes, kw) - extract_marker(plotattributes, kw) - vis2 = GL.gl_scatter(copy(points), kw) - vis = [vis; vis2] - end - if plotattributes[:fillrange] != nothing - kw = copy(kw_args) - fr = plotattributes[:fillrange] - ps = if all(x-> x >= 0, diff(plotattributes[:x])) # if is monotonic - vcat(points, Point2f0[(points[i][1], _cycle(fr, i)) for i=length(points):-1:1]) - else - points - end - extract_c(plotattributes, kw, :fill) - vis = [GL.gl_poly(ps, kw), vis] - end - elseif st in (:scatter, :scatter3d) #|| plotattributes[:markershape] != :none - extract_marker(plotattributes, kw_args) - points = extract_points(plotattributes) - vis = GL.gl_scatter(points, kw_args) - elseif st == :shape - extract_c(plotattributes, kw_args, :fill) - vis = GL.gl_shape(plotattributes, kw_args) - elseif st == :contour - x,y,z = extract_surface(plotattributes) - z = transpose_z(plotattributes, z, false) - extract_extrema(plotattributes, kw_args) - extract_gradient(plotattributes, kw_args, :fill) - kw_args[:fillrange] = plotattributes[:fillrange] - kw_args[:levels] = plotattributes[:levels] - - vis = GL.gl_contour(x,y,z, kw_args) - elseif st == :heatmap - x,y,z = extract_surface(plotattributes) - extract_gradient(plotattributes, kw_args, :fill) - extract_extrema(plotattributes, kw_args) - extract_limits(sp, plotattributes, kw_args) - vis = GL.gl_heatmap(x,y,z, kw_args) - elseif st == :bar - extract_c(plotattributes, kw_args, :fill) - extract_stroke(plotattributes, kw_args, :marker) - vis = gl_bar(plotattributes, kw_args) - elseif st == :image - extract_extrema(plotattributes, kw_args) - vis = GL.gl_image(plotattributes[:z].surf, kw_args) - elseif st == :boxplot - extract_c(plotattributes, kw_args, :fill) - vis = gl_boxplot(plotattributes, kw_args) - elseif st == :volume - volume = plotattributes[:y] - _plotattributes = copy(plotattributes) - _plotattributes[:y] = 0:1 - _plotattributes[:x] = 0:1 - kw_args = KW() - extract_gradient(_plotattributes, kw_args, :fill) - vis = visualize(volume.v, Style(:default), kw_args) - else - error("failed to display plot type $st") - end - - isa(vis, Array) && isempty(vis) && continue # nothing to see here - - GLVisualize._view(vis, sp_screen, camera=:perspective) - if haskey(plotattributes, :hover) && !(plotattributes[:hover] in (false, :none, nothing)) - hover(vis, plotattributes[:hover], sp_screen) - end - if isdefined(:GLPlot) && isdefined(Main.GLPlot, :(register_plot!)) - del_signal = Main.GLPlot.register_plot!(vis, sp_screen, create_gizmo=false) - append!(_glplot_deletes, del_signal) - end - anns = series[:series_annotations] - for (x, y, str, font) in EachAnn(anns, plotattributes[:x], plotattributes[:y]) - txt_args = Dict{Symbol, Any}(:model => eye(GLAbstraction.Mat4f0)) - x, y = Reactive.value(model_m) * GeometryTypes.Vec{4, Float32}(x, y, 0, 1) - extract_font(font, txt_args) - t = glvisualize_text(Point2f0(x, y), PlotText(str, font), txt_args) - GLVisualize._view(t, sp_screen, camera = :perspective) - end - - end - generate_legend(sp, sp_screen, model_m) - if _3d - GLAbstraction.center!(sp_screen) - end - GLAbstraction.post_empty() - yield() - end -end - -function _show(io::IO, ::MIME"image/png", plt::Plot{GLVisualizeBackend}) - _display(plt, false) - GLWindow.poll_glfw() - if Base.n_avail(Reactive._messages) > 0 - Reactive.run_till_now() - end - yield() - GLWindow.render_frame(GLWindow.rootscreen(plt.o)) - GLWindow.swapbuffers(plt.o) - buff = GLWindow.screenbuffer(plt.o) - png = map(RGB{U8}, buff) - FileIO.save(FileIO.Stream(FileIO.DataFormat{:PNG}, io), png) -end - - -function gl_image(img, kw_args) - rect = kw_args[:primitive] - kw_args[:primitive] = GeometryTypes.SimpleRectangle{Float32}(rect.x, rect.y, rect.w, rect.h) - visualize(img, Style(:default), kw_args) -end - -function handle_segment(lines, line_segments, points::Vector{P}, segment) where P - (isempty(segment) || length(segment) < 2) && return - if length(segment) == 2 - append!(line_segments, view(points, segment)) - elseif length(segment) == 3 - p = view(points, segment) - push!(line_segments, p[1], p[2], p[2], p[3]) - else - append!(lines, view(points, segment)) - push!(lines, P(NaN)) - end -end - -function gl_lines(points, kw_args) - result = [] - isempty(points) && return result - P = eltype(points) - lines = P[] - line_segments = P[] - last = 1 - for (i,p) in enumerate(points) - if isnan(p) || i==length(points) - _i = isnan(p) ? i-1 : i - handle_segment(lines, line_segments, points, last:_i) - last = i+1 - end - end - if !isempty(lines) - pop!(lines) # remove last NaN - push!(result, visualize(lines, Style(:lines), kw_args)) - end - if !isempty(line_segments) - push!(result, visualize(line_segments, Style(:linesegment), kw_args)) - end - return result -end - -function gl_shape(plotattributes, kw_args) - points = Plots.extract_points(plotattributes) - result = [] - for rng in iter_segments(plotattributes[:x], plotattributes[:y]) - ps = points[rng] - meshes = gl_poly(ps, kw_args) - append!(result, meshes) - end - result -end - - - -function gl_scatter(points, kw_args) - prim = get(kw_args, :primitive, GeometryTypes.Circle) - if isa(prim, GLNormalMesh) - if haskey(kw_args, :model) - p = get(kw_args, :perspective, eye(GeometryTypes.Mat4f0)) - kw_args[:scale] = GLAbstraction.const_lift(kw_args[:model], kw_args[:scale], p) do m, sc, p - s = Vec3f0(m[1,1], m[2,2], m[3,3]) - ps = Vec3f0(p[1,1], p[2,2], p[3,3]) - r = sc ./ (s .* ps) - r - end - end - else # 2D prim - kw_args[:scale] = to_vec(Vec2f0, kw_args[:scale]) - end - - if haskey(kw_args, :stroke_width) - s = Reactive.value(kw_args[:scale]) - sw = kw_args[:stroke_width] - if sw*5 > _cycle(Reactive.value(s), 1)[1] # restrict marker stroke to 1/10th of scale (and handle arrays of scales) - kw_args[:stroke_width] = s[1] / 5f0 - end - end - kw_args[:scale_primitive] = false - if isa(prim, String) - kw_args[:position] = points - if !isa(kw_args[:scale], Vector) # if not vector, we can assume it's relative scale - kw_args[:relative_scale] = kw_args[:scale] - delete!(kw_args, :scale) - end - return visualize(prim, Style(:default), kw_args) - end - - visualize((prim, points), Style(:default), kw_args) -end - - -function gl_poly(points, kw_args) - last(points) == first(points) && pop!(points) - polys = GeometryTypes.split_intersections(points) - result = [] - for poly in polys - mesh = GLNormalMesh(poly) # make polygon - if !isempty(GeometryTypes.faces(mesh)) # check if polygonation has any faces - push!(result, GLVisualize.visualize(mesh, Style(:default), kw_args)) - else - @warn("Couldn't draw the polygon: $points") - end - end - result -end - - - - -function gl_surface(x,y,z, kw_args) - if isa(x, AbstractRange) && isa(y, AbstractRange) - main = z - kw_args[:ranges] = (x, y) - else - if isa(x, AbstractMatrix) && isa(y, AbstractMatrix) - main = map(s->map(Float32, s), (x, y, z)) - elseif isa(x, AbstractVector) || isa(y, AbstractVector) - x = Float32[x[i] for i = 1:size(z,1), j = 1:size(z,2)] - y = Float32[y[j] for i = 1:size(z,1), j = 1:size(z,2)] - main = (x, y, map(Float32, z)) - else - error("surface: combination of types not supported: $(typeof(x)) $(typeof(y)) $(typeof(z))") - end - if get(kw_args, :wireframe, false) - points = map(Point3f0, zip(vec(x), vec(y), vec(z))) - faces = Cuint[] - idx = (i,j) -> CartesianIndices(size(z), i, j) - 1 - for i=1:size(z,1), j=1:size(z,2) - - i < size(z,1) && push!(faces, idx(i, j), idx(i+1, j)) - j < size(z,2) && push!(faces, idx(i, j), idx(i, j+1)) - - end - color = get(kw_args, :stroke_color, RGBA{Float32}(0,0,0,1)) - kw_args[:color] = color - kw_args[:thickness] = Float32(get(kw_args, :stroke_width, 1f0)) - kw_args[:indices] = faces - delete!(kw_args, :stroke_color) - delete!(kw_args, :stroke_width) - - return visualize(points, Style(:linesegment), kw_args) - end - end - return visualize(main, Style(:surface), kw_args) -end - - -function gl_contour(x, y, z, kw_args) - if kw_args[:fillrange] != nothing - - delete!(kw_args, :intensity) - I = GLVisualize.Intensity{Float32} - main = [I(z[j,i]) for i=1:size(z, 2), j=1:size(z, 1)] - return visualize(main, Style(:default), kw_args) - - else - h = kw_args[:levels] - T = eltype(z) - levels = Contour.contours(map(T, x), map(T, y), z, h) - result = Point2f0[] - zmin, zmax = get(kw_args, :limits, Vec2f0(ignorenan_extrema(z))) - cmap = get(kw_args, :color_map, get(kw_args, :color, RGBA{Float32}(0,0,0,1))) - colors = RGBA{Float32}[] - for c in levels.contours - for elem in c.lines - append!(result, elem.vertices) - push!(result, Point2f0(NaN32)) - col = GLVisualize.color_lookup(cmap, c.level, zmin, zmax) - append!(colors, fill(col, length(elem.vertices) + 1)) - end - end - kw_args[:color] = colors - kw_args[:color_map] = nothing - kw_args[:color_norm] = nothing - kw_args[:intensity] = nothing - return visualize(result, Style(:lines),kw_args) - end -end - - -function gl_heatmap(x,y,z, kw_args) - get!(kw_args, :color_norm, Vec2f0(ignorenan_extrema(z))) - get!(kw_args, :color_map, Plots.make_gradient(cgrad())) - delete!(kw_args, :intensity) - I = GLVisualize.Intensity{Float32} - heatmap = I[z[j,i] for i=1:size(z, 2), j=1:size(z, 1)] - tex = GLAbstraction.Texture(heatmap, minfilter=:nearest) - kw_args[:stroke_width] = 0f0 - kw_args[:levels] = 1f0 - visualize(tex, Style(:default), kw_args) -end - - - - -""" -Ugh, so much special casing (╯°□°)╯︵ ┻━┻ -""" -function label_scatter(plotattributes, w, ho) - kw = KW() - extract_stroke(plotattributes, kw) - extract_marker(plotattributes, kw) - kw[:scale] = Vec2f0(w/2) - kw[:offset] = Vec2f0(-w/4) - if haskey(kw, :intensity) - cmap = kw[:color_map] - norm = kw[:color_norm] - kw[:color] = GLVisualize.color_lookup(cmap, kw[:intensity][1], norm) - delete!(kw, :intensity) - delete!(kw, :color_map) - delete!(kw, :color_norm) - else - color = get(kw, :color, nothing) - kw[:color] = isa(color, Array) ? first(color) : color - end - strcolor = get(kw, :stroke_color, RGBA{Float32}(0,0,0,0)) - kw[:stroke_color] = isa(strcolor, Array) ? first(strcolor) : strcolor - p = get(kw, :primitive, GeometryTypes.Circle) - if isa(p, GLNormalMesh) - bb = GeometryTypes.AABB{Float32}(GeometryTypes.vertices(p)) - bbw = GeometryTypes.widths(bb) - if isapprox(bbw[3], 0) - bbw = Vec3f0(bbw[1], bbw[2], 1) - end - mini = minimum(bb) - m = GLAbstraction.translationmatrix(-mini) - m *= GLAbstraction.scalematrix(1 ./ bbw) - kw[:primitive] = m * p - kw[:scale] = Vec3f0(w/2) - delete!(kw, :offset) - end - if isa(p, Array) - kw[:primitive] = GeometryTypes.Circle - end - GL.gl_scatter(Point2f0[(w/2, ho)], kw) -end - - -function make_label(sp, series, i) - GL = Plots - w, gap, ho = 20f0, 5f0, 5 - result = [] - plotattributes = series.plotattributes - st = plotattributes[:seriestype] - kw_args = KW() - if (st in (:path, :path3d, :straightline)) && plotattributes[:linewidth] > 0 - points = Point2f0[(0, ho), (w, ho)] - kw = KW() - extract_linestyle(plotattributes, kw) - append!(result, GL.gl_lines(points, kw)) - if plotattributes[:markershape] != :none - push!(result, label_scatter(plotattributes, w, ho)) - end - elseif st in (:scatter, :scatter3d) #|| plotattributes[:markershape] != :none - push!(result, label_scatter(plotattributes, w, ho)) - else - extract_c(plotattributes, kw_args, :fill) - if isa(kw_args[:color], AbstractVector) - kw_args[:color] = first(kw_args[:color]) - end - push!(result, visualize( - GeometryTypes.SimpleRectangle(-w/2, ho-w/4, w/2, w/2), - Style(:default), kw_args - )) - end - labeltext = if isa(series[:label], Array) - i += 1 - series[:label][i] - else - series[:label] - end - ft = legendfont(sp) - font = Plots.Font(ft.family, ft.pointsize, :left, :bottom, 0.0, ft.color) - xy = Point2f0(w+gap, 0.0) - kw = Dict(:model => text_model(font, xy), :scale_primitive=>false) - extract_font(font, kw) - t = PlotText(labeltext, font) - push!(result, glvisualize_text(xy, t, kw)) - GLAbstraction.Context(result...), i -end - - -function generate_legend(sp, screen, model_m) - legend = GLAbstraction.Context[] - if sp[:legend] != :none - i = 0 - for series in series_list(sp) - should_add_to_legend(series) || continue - result, i = make_label(sp, series, i) - push!(legend, result) - end - if isempty(legend) - return - end - list = visualize(legend, gap=Vec3f0(0,5,0)) - bb = GLAbstraction._boundingbox(list) - wx,wy,_ = GeometryTypes.widths(bb) - xmin, _ = Plots.axis_limits(sp[:xaxis]) - _, ymax = Plots.axis_limits(sp[:yaxis]) - area = map(model_m) do m - p = m * GeometryTypes.Vec4f0(xmin, ymax, 0, 1) - h = round(Int, wy)+20 - w = round(Int, wx)+20 - x,y = round(Int, p[1])+30, round(Int, p[2]-h)-30 - GeometryTypes.SimpleRectangle(x, y, w, h) - end - sscren = GLWindow.Screen( - screen, area = area, - color = sp[:background_color_legend], - stroke = (2f0, RGBA(0.3, 0.3, 0.3, 0.9)) - ) - GLAbstraction.translate!(list, Vec3f0(10,10,0)) - GLVisualize._view(list, sscren, camera=:fixed_pixel) - end - return -end diff --git a/src/backends/gr.jl b/src/backends/gr.jl index 267875f9..505ad39f 100644 --- a/src/backends/gr.jl +++ b/src/backends/gr.jl @@ -3,65 +3,6 @@ # significant contributions by @jheinen -const _gr_attr = merge_with_base_supported([ - :annotations, - :background_color_legend, :background_color_inside, :background_color_outside, - :foreground_color_legend, :foreground_color_grid, :foreground_color_axis, - :foreground_color_text, :foreground_color_border, - :label, - :seriescolor, :seriesalpha, - :linecolor, :linestyle, :linewidth, :linealpha, - :markershape, :markercolor, :markersize, :markeralpha, - :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, - :fillrange, :fillcolor, :fillalpha, - :bins, - :layout, - :title, :window_title, - :guide, :guide_position, :lims, :ticks, :scale, :flip, - :match_dimensions, - :titlefontfamily, :titlefontsize, :titlefonthalign, :titlefontvalign, - :titlefontrotation, :titlefontcolor, - :legendfontfamily, :legendfontsize, :legendfonthalign, :legendfontvalign, - :legendfontrotation, :legendfontcolor, - :tickfontfamily, :tickfontsize, :tickfonthalign, :tickfontvalign, - :tickfontrotation, :tickfontcolor, - :guidefontfamily, :guidefontsize, :guidefonthalign, :guidefontvalign, - :guidefontrotation, :guidefontcolor, - :grid, :gridalpha, :gridstyle, :gridlinewidth, - :legend, :legendtitle, :colorbar, :colorbar_title, - :fill_z, :line_z, :marker_z, :levels, - :ribbon, :quiver, - :orientation, - :overwrite_figure, - :polar, - :aspect_ratio, - :normalize, :weights, - :inset_subplots, - :bar_width, - :arrow, - :framestyle, - :tick_direction, - :camera, - :contour_labels, -]) -const _gr_seriestype = [ - :path, :scatter, :straightline, - :heatmap, :pie, :image, - :contour, :path3d, :scatter3d, :surface, :wireframe, - :shape -] -const _gr_style = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot] -const _gr_marker = _allMarkers -const _gr_scale = [:identity, :log10] -is_marker_supported(::GRBackend, shape::Shape) = true - -function add_backend_string(::GRBackend) - """ - Pkg.add("GR") - Pkg.build("GR") - """ -end - import GR export GR @@ -661,11 +602,19 @@ function _update_min_padding!(sp::Subplot{GRBackend}) end # Add margin for x label if sp[:xaxis][:guide] != "" - bottompad += 4mm + if sp[:xaxis][:guide_position] == :top || (sp[:xaxis][:guide_position] == :auto && sp[:xaxis][:mirror] == true) + toppad += 4mm + else + bottompad += 4mm + end end # Add margin for y label if sp[:yaxis][:guide] != "" - leftpad += 4mm + if sp[:yaxis][:guide_position] == :right || (sp[:yaxis][:guide_position] == :auto && sp[:yaxis][:mirror] == true) + rightpad += 4mm + else + leftpad += 4mm + end end if sp[:colorbar_title] != "" rightpad += 4mm @@ -722,7 +671,7 @@ function gr_display(sp::Subplot{GRBackend}, w, h, viewport_canvas) outside_ticks = true for ax in (sp[:xaxis], sp[:yaxis]) v = series[ax[:letter]] - if diff(collect(extrema(diff(v))))[1] > 1e-6*std(v) + if length(v) > 1 && diff(collect(extrema(diff(v))))[1] > 1e-6*std(v) @warn("GR: heatmap only supported with equally spaced data.") end end @@ -855,12 +804,12 @@ function gr_display(sp::Subplot{GRBackend}, w, h, viewport_canvas) # axis lines if xaxis[:showaxis] - gr_set_line(1, :solid, xaxis[:foreground_color_axis]) + gr_set_line(1, :solid, xaxis[:foreground_color_border]) GR.setclip(0) gr_polyline(coords(xspine_segs)...) end if yaxis[:showaxis] - gr_set_line(1, :solid, yaxis[:foreground_color_axis]) + gr_set_line(1, :solid, yaxis[:foreground_color_border]) GR.setclip(0) gr_polyline(coords(yspine_segs)...) end @@ -962,7 +911,7 @@ function gr_display(sp::Subplot{GRBackend}, w, h, viewport_canvas) if xaxis[:guide] != "" gr_set_font(guidefont(xaxis)) - if xaxis[:guide_position] == :top + if xaxis[:guide_position] == :top || (xaxis[:guide_position] == :auto && xaxis[:mirror] == true) GR.settextalign(GR.TEXT_HALIGN_CENTER, GR.TEXT_VALIGN_TOP) gr_text(gr_view_xcenter(), viewport_subplot[4], xaxis[:guide]) else @@ -974,7 +923,7 @@ function gr_display(sp::Subplot{GRBackend}, w, h, viewport_canvas) if yaxis[:guide] != "" gr_set_font(guidefont(yaxis)) GR.setcharup(-1, 0) - if yaxis[:guide_position] == :left + if yaxis[:guide_position] == :right || (yaxis[:guide_position] == :auto && yaxis[:mirror] == true) GR.settextalign(GR.TEXT_HALIGN_CENTER, GR.TEXT_VALIGN_BOTTOM) gr_text(viewport_subplot[2], gr_view_ycenter(), yaxis[:guide]) else @@ -1109,7 +1058,11 @@ function gr_display(sp::Subplot{GRBackend}, w, h, viewport_canvas) if length(x) == length(y) == length(z) GR.trisurface(x, y, z) else - GR.gr3.surface(x, y, z, GR.OPTION_COLORED_MESH) + try + GR.gr3.surface(x, y, z, GR.OPTION_COLORED_MESH) + catch + GR.surface(x, y, z, GR.OPTION_COLORED_MESH) + end end else GR.setfillcolorind(0) diff --git a/src/backends/hdf5.jl b/src/backends/hdf5.jl index 28dd767d..9b357216 100644 --- a/src/backends/hdf5.jl +++ b/src/backends/hdf5.jl @@ -16,16 +16,19 @@ Read from .hdf5 file using: #==TODO =============================================================================== - 1. Support more features - - SeriesAnnotations & GridLayout known to be missing. - 3. Improve error handling. + 1. Support more features. + - GridLayout known not to be working. + 2. Improve error handling. - Will likely crash if file format is off. - 2. Save data in a folder parallel to "plot". + 3. Save data in a folder parallel to "plot". - Will make it easier for users to locate data. - Use HDF5 reference to link data? - 3. Develop an actual versioned file format. + 4. Develop an actual versioned file format. - Should have some form of backward compatibility. - Should be reliable for archival purposes. + 5. Fix construction of plot object with hdf5plot_read. + - Not building object correctly when backends do not natively support + a certain feature (ex: :steppre) ==# import FixedPointNumbers: N0f8 #In core Julia @@ -56,53 +59,13 @@ const HDF5PLOT_PLOTREF = HDF5Plot_PlotRef(nothing) #Simple sub-structures that can just be written out using _hdf5plot_gwritefields: const HDF5PLOT_SIMPLESUBSTRUCT = Union{Font, BoundingBox, - GridLayout, RootLayout, ColorGradient, SeriesAnnotations, PlotText + GridLayout, RootLayout, ColorGradient, SeriesAnnotations, PlotText, + Shape, } #== ===============================================================================# - -const _hdf5_attr = merge_with_base_supported([ - :annotations, - :background_color_legend, :background_color_inside, :background_color_outside, - :foreground_color_grid, :foreground_color_legend, :foreground_color_title, - :foreground_color_axis, :foreground_color_border, :foreground_color_guide, :foreground_color_text, - :label, - :linecolor, :linestyle, :linewidth, :linealpha, - :markershape, :markercolor, :markersize, :markeralpha, - :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, - :fillrange, :fillcolor, :fillalpha, - :bins, :bar_width, :bar_edges, :bar_position, - :title, :title_location, :titlefont, - :window_title, - :guide, :lims, :ticks, :scale, :flip, :rotation, - :tickfont, :guidefont, :legendfont, - :grid, :legend, :colorbar, - :marker_z, :line_z, :fill_z, - :levels, - :ribbon, :quiver, :arrow, - :orientation, - :overwrite_figure, - :polar, - :normalize, :weights, - :contours, :aspect_ratio, - :match_dimensions, - :clims, - :inset_subplots, - :dpi, - :colorbar_title, - ]) -const _hdf5_seriestype = [ - :path, :steppre, :steppost, :shape, :straightline, - :scatter, :hexbin, #:histogram2d, :histogram, - # :bar, - :heatmap, :pie, :image, - :contour, :contour3d, :path3d, :scatter3d, :surface, :wireframe - ] -const _hdf5_style = [:auto, :solid, :dash, :dot, :dashdot] -const _hdf5_marker = vcat(_allMarkers, :pixel) -const _hdf5_scale = [:identity, :ln, :log2, :log10] is_marker_supported(::HDF5Backend, shape::Shape) = true if length(HDF5PLOT_MAP_TELEM2STR) < 1 @@ -125,7 +88,8 @@ if length(HDF5PLOT_MAP_TELEM2STR) < 1 "GRIDLAYOUT" => GridLayout, "ROOTLAYOUT" => RootLayout, "SERIESANNOTATIONS" => SeriesAnnotations, -# "PLOTTEXT" => PlotText, + "PLOTTEXT" => PlotText, + "SHAPE" => Shape, "COLORGRADIENT" => ColorGradient, "AXIS" => Axis, "SURFACE" => Surface, @@ -284,6 +248,14 @@ end # ---------------------------------------------------------------- function _hdf5plot_gwrite(grp, k::String, v) #Default + T = typeof(v) + if !(T <: Number || T <: String) + tstr = string(T) + path = HDF5.name(grp) * "/" * k + @info("Type not supported: $tstr\npath: $path") +# @show v + return + end grp[k] = v _hdf5plot_writetype(grp, k, HDF5PlotNative) end @@ -338,10 +310,6 @@ function _hdf5plot_gwrite(grp, k::String, v::Colorant) end #Custom vector (when not using simple numeric type): function _hdf5plot_gwritearray(grp, k::String, v::Array{T}) where T - if "annotations" == k; - return #Hack. Does not yet support annotations. - end - vgrp = HDF5.g_create(grp, k) _hdf5plot_writetype(vgrp, Array) #ANY sz = size(v) @@ -351,7 +319,7 @@ function _hdf5plot_gwritearray(grp, k::String, v::Array{T}) where T coord = lidx[iter] elem = v[iter] idxstr = join(coord, "_") - _hdf5plot_gwrite(vgrp, "v$idxstr", v[iter]) + _hdf5plot_gwrite(vgrp, "v$idxstr", elem) end _hdf5plot_gwrite(vgrp, "dim", [sz...]) @@ -402,10 +370,6 @@ end # return # end -function _hdf5plot_gwrite(grp, k::String, v::SeriesAnnotations) - #Currently no support for SeriesAnnotations - return -end function _hdf5plot_gwrite(grp, k::String, v::Subplot) grp = HDF5.g_create(grp, k) _hdf5plot_gwrite(grp, "index", v[:subplot_index]) @@ -528,6 +492,29 @@ function _hdf5plot_read(grp, k::String, T::Type{HDF5CTuple}, dtid) v = _hdf5plot_read(grp, k, Array, dtid) return tuple(v...) end +function _hdf5plot_read(grp, k::String, T::Type{PlotText}, dtid) + grp = HDF5.g_open(grp, k) + + str = _hdf5plot_read(grp, "str") + font = _hdf5plot_read(grp, "font") + return PlotText(str, font) +end +function _hdf5plot_read(grp, k::String, T::Type{SeriesAnnotations}, dtid) + grp = HDF5.g_open(grp, k) + + strs = _hdf5plot_read(grp, "strs") + font = _hdf5plot_read(grp, "font") + baseshape = _hdf5plot_read(grp, "baseshape") + scalefactor = _hdf5plot_read(grp, "scalefactor") + return SeriesAnnotations(strs, font, baseshape, scalefactor) +end +function _hdf5plot_read(grp, k::String, T::Type{Shape}, dtid) + grp = HDF5.g_open(grp, k) + + x = _hdf5plot_read(grp, "x") + y = _hdf5plot_read(grp, "y") + return Shape(x, y) +end function _hdf5plot_read(grp, k::String, T::Type{ColorGradient}, dtid) grp = HDF5.g_open(grp, k) @@ -601,11 +588,6 @@ end function _hdf5plot_read(sp::Subplot, subpath::String, f) f = f::HDF5.HDF5File #Assert - grp = HDF5.g_open(f, _hdf5_plotelempath("$subpath/attr")) - kwlist = KW() - _hdf5plot_read(grp, kwlist) - _hdf5_merge!(sp.attr, kwlist) - grp = HDF5.g_open(f, _hdf5_plotelempath("$subpath/series_list")) nseries = _hdf5plot_readcount(grp) @@ -617,6 +599,12 @@ function _hdf5plot_read(sp::Subplot, subpath::String, f) _hdf5_merge!(sp.series_list[end].plotattributes, kwlist) end + #Perform after adding series... otherwise values get overwritten: + grp = HDF5.g_open(f, _hdf5_plotelempath("$subpath/attr")) + kwlist = KW() + _hdf5plot_read(grp, kwlist) + _hdf5_merge!(sp.attr, kwlist) + return end diff --git a/src/backends/inspectdr.jl b/src/backends/inspectdr.jl index 56fd7f32..bbc268a3 100644 --- a/src/backends/inspectdr.jl +++ b/src/backends/inspectdr.jl @@ -14,61 +14,6 @@ Add in functionality to Plots.jl: =# # --------------------------------------------------------------------------- -#TODO: remove features -const _inspectdr_attr = merge_with_base_supported([ - :annotations, - :background_color_legend, :background_color_inside, :background_color_outside, - # :foreground_color_grid, - :foreground_color_legend, :foreground_color_title, - :foreground_color_axis, :foreground_color_border, :foreground_color_guide, :foreground_color_text, - :label, - :seriescolor, :seriesalpha, - :linecolor, :linestyle, :linewidth, :linealpha, - :markershape, :markercolor, :markersize, :markeralpha, - :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, - :markerstrokestyle, #Causes warning not to have it... what is this? - :fillcolor, :fillalpha, #:fillrange, -# :bins, :bar_width, :bar_edges, :bar_position, - :title, :title_location, - :window_title, - :guide, :lims, :scale, #:ticks, :flip, :rotation, - :titlefontfamily, :titlefontsize, :titlefontcolor, - :legendfontfamily, :legendfontsize, :legendfontcolor, - :tickfontfamily, :tickfontsize, :tickfontcolor, - :guidefontfamily, :guidefontsize, :guidefontcolor, - :grid, #:gridalpha, :gridstyle, :gridlinewidth, #alhpa & linewidth are per plot - not per subplot - :legend, #:legendtitle, :colorbar, -# :marker_z, -# :line_z, -# :levels, - # :ribbon, :quiver, :arrow, -# :orientation, - :overwrite_figure, - :polar, -# :normalize, :weights, -# :contours, :aspect_ratio, - :match_dimensions, -# :clims, -# :inset_subplots, - :dpi, -# :colorbar_title, - ]) -const _inspectdr_style = [:auto, :solid, :dash, :dot, :dashdot] -const _inspectdr_seriestype = [ - :path, :scatter, :shape, :straightline, #, :steppre, :steppost - ] -#see: _allMarkers, _shape_keys -const _inspectdr_marker = Symbol[ - :none, :auto, - :circle, :rect, :diamond, - :cross, :xcross, - :utriangle, :dtriangle, :rtriangle, :ltriangle, - :pentagon, :hexagon, :heptagon, :octagon, - :star4, :star5, :star6, :star7, :star8, - :vline, :hline, :+, :x, -] - -const _inspectdr_scale = [:identity, :ln, :log2, :log10] is_marker_supported(::InspectDRBackend, shape::Shape) = true diff --git a/src/backends/pgfplots.jl b/src/backends/pgfplots.jl index 26865bb9..e060a2f1 100644 --- a/src/backends/pgfplots.jl +++ b/src/backends/pgfplots.jl @@ -2,47 +2,6 @@ # significant contributions by: @pkofod -const _pgfplots_attr = merge_with_base_supported([ - :annotations, - :background_color_legend, - :background_color_inside, - # :background_color_outside, - # :foreground_color_legend, - :foreground_color_grid, :foreground_color_axis, - :foreground_color_text, :foreground_color_border, - :label, - :seriescolor, :seriesalpha, - :linecolor, :linestyle, :linewidth, :linealpha, - :markershape, :markercolor, :markersize, :markeralpha, - :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, :markerstrokestyle, - :fillrange, :fillcolor, :fillalpha, - :bins, - # :bar_width, :bar_edges, - :title, - # :window_title, - :guide, :guide_position, :lims, :ticks, :scale, :flip, :rotation, - :tickfont, :guidefont, :legendfont, - :grid, :legend, - :colorbar, :colorbar_title, - :fill_z, :line_z, :marker_z, :levels, - # :ribbon, :quiver, :arrow, - # :orientation, - # :overwrite_figure, - :polar, - # :normalize, :weights, :contours, - :aspect_ratio, - # :match_dimensions, - :tick_direction, - :framestyle, - :camera, - :contour_labels, - ]) -const _pgfplots_seriestype = [:path, :path3d, :scatter, :steppre, :stepmid, :steppost, :histogram2d, :ysticks, :xsticks, :contour, :shape, :straightline,] -const _pgfplots_style = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot] -const _pgfplots_marker = [:none, :auto, :circle, :rect, :diamond, :utriangle, :dtriangle, :cross, :xcross, :star5, :pentagon, :hline] #vcat(_allMarkers, Shape) -const _pgfplots_scale = [:identity, :ln, :log2, :log10] - - # -------------------------------------------------------------------------------------- const _pgfplots_linestyles = KW( @@ -446,7 +405,7 @@ function pgf_axis(sp::Subplot, letter) if framestyle == :zerolines push!(style, string("extra ", letter, " ticks = 0")) push!(style, string("extra ", letter, " tick labels = ")) - push!(style, string("extra ", letter, " tick style = {grid = major, major grid style = {", pgf_linestyle(pgf_thickness_scaling(sp), axis[:foreground_color_axis], 1.0), "}}")) + push!(style, string("extra ", letter, " tick style = {grid = major, major grid style = {", pgf_linestyle(pgf_thickness_scaling(sp), axis[:foreground_color_border], 1.0), "}}")) end if !axis[:showaxis] @@ -455,7 +414,7 @@ function pgf_axis(sp::Subplot, letter) if !axis[:showaxis] || framestyle in (:zerolines, :grid, :none) push!(style, string(letter, " axis line style = {draw opacity = 0}")) else - push!(style, string(letter, " axis line style = {", pgf_linestyle(pgf_thickness_scaling(sp), axis[:foreground_color_axis], 1.0), "}")) + push!(style, string(letter, " axis line style = {", pgf_linestyle(pgf_thickness_scaling(sp), axis[:foreground_color_border], 1.0), "}")) end # return the style list and KW args diff --git a/src/backends/plotly.jl b/src/backends/plotly.jl index 3e525b5b..569e05e3 100644 --- a/src/backends/plotly.jl +++ b/src/backends/plotly.jl @@ -1,60 +1,6 @@ # https://plot.ly/javascript/getting-started -const _plotly_attr = merge_with_base_supported([ - :annotations, - :background_color_legend, :background_color_inside, :background_color_outside, - :foreground_color_legend, :foreground_color_guide, - :foreground_color_grid, :foreground_color_axis, - :foreground_color_text, :foreground_color_border, - :foreground_color_title, - :label, - :seriescolor, :seriesalpha, - :linecolor, :linestyle, :linewidth, :linealpha, - :markershape, :markercolor, :markersize, :markeralpha, - :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, :markerstrokestyle, - :fillrange, :fillcolor, :fillalpha, - :bins, - :title, :title_location, - :titlefontfamily, :titlefontsize, :titlefonthalign, :titlefontvalign, - :titlefontcolor, - :legendfontfamily, :legendfontsize, :legendfontcolor, - :tickfontfamily, :tickfontsize, :tickfontcolor, - :guidefontfamily, :guidefontsize, :guidefontcolor, - :window_title, - :guide, :lims, :ticks, :scale, :flip, :rotation, - :tickfont, :guidefont, :legendfont, - :grid, :gridalpha, :gridlinewidth, - :legend, :colorbar, :colorbar_title, - :marker_z, :fill_z, :line_z, :levels, - :ribbon, :quiver, - :orientation, - # :overwrite_figure, - :polar, - :normalize, :weights, - # :contours, - :aspect_ratio, - :hover, - :inset_subplots, - :bar_width, - :clims, - :framestyle, - :tick_direction, - :camera, - :contour_labels, - ]) - -const _plotly_seriestype = [ - :path, :scatter, :pie, :heatmap, - :contour, :surface, :wireframe, :path3d, :scatter3d, :shape, :scattergl, - :straightline -] -const _plotly_style = [:auto, :solid, :dash, :dot, :dashdot] -const _plotly_marker = [ - :none, :auto, :circle, :rect, :diamond, :utriangle, :dtriangle, - :cross, :xcross, :pentagon, :hexagon, :octagon, :vline, :hline -] -const _plotly_scale = [:identity, :log10] is_subplot_supported(::PlotlyBackend) = true # is_string_supported(::PlotlyBackend) = true const _plotly_framestyles = [:box, :axes, :zerolines, :grid, :none] @@ -71,30 +17,9 @@ end # -------------------------------------------------------------------------------------- +const plotly_remote_file_path = "https://cdn.plot.ly/plotly-latest.min.js" -const _plotly_js_path = joinpath(dirname(@__FILE__), "..", "..", "deps", "plotly-latest.min.js") -const _plotly_js_path_remote = "https://cdn.plot.ly/plotly-latest.min.js" - -_js_code = open(read, _plotly_js_path, "r") - -# borrowed from https://github.com/plotly/plotly.py/blob/2594076e29584ede2d09f2aa40a8a195b3f3fc66/plotly/offline/offline.py#L64-L71 c/o @spencerlyon2 -_js_script = """ - -""" - -# if we're in IJulia call setupnotebook to load js and css -if isijulia() - display("text/html", _js_script) -end - # if isatom() # import Atom # Atom.@msg evaljs(_js_code) @@ -102,8 +27,6 @@ end using UUIDs push!(_initialized_backends, :plotly) - - # ---------------------------------------------------------------- const _plotly_legend_pos = KW( @@ -115,7 +38,7 @@ const _plotly_legend_pos = KW( :bottomright => [1., 0.], :topright => [1., 1.], :topleft => [0., 1.] - ) +) plotly_legend_pos(pos::Symbol) = get(_plotly_legend_pos, pos, [1.,1.]) plotly_legend_pos(v::Tuple{S,T}) where {S<:Real, T<:Real} = v @@ -882,12 +805,27 @@ plotly_series_json(plt::Plot) = JSON.json(plotly_series(plt)) # ---------------------------------------------------------------- -const _use_remote = Ref(false) +const ijulia_initialized = Ref(false) function html_head(plt::Plot{PlotlyBackend}) - jsfilename = _use_remote[] ? _plotly_js_path_remote : ("file://" * _plotly_js_path) - # "" - "" + local_file = ("file://" * plotly_local_file_path) + plotly = use_local_dependencies[] ? local_file : plotly_remote_file_path + if isijulia() && !ijulia_initialized[] + # using requirejs seems to be key to load a js depency in IJulia! + # https://requirejs.org/docs/start.html + # https://github.com/JuliaLang/IJulia.jl/issues/345 + display("text/html", """ + + """) + ijulia_initialized[] = true + end + # IJulia just needs one initialization + isijulia() && return "" + return "" end function html_body(plt::Plot{PlotlyBackend}, style = nothing) @@ -908,8 +846,8 @@ end function js_body(plt::Plot{PlotlyBackend}, uuid) js = """ - PLOT = document.getElementById('$(uuid)'); - Plotly.plot(PLOT, $(plotly_series_json(plt)), $(plotly_layout_json(plt))); + PLOT = document.getElementById('$(uuid)'); + Plotly.plot(PLOT, $(plotly_series_json(plt)), $(plotly_layout_json(plt))); """ end diff --git a/src/backends/plotlyjs.jl b/src/backends/plotlyjs.jl index 70a7c3c3..a863ae92 100644 --- a/src/backends/plotlyjs.jl +++ b/src/backends/plotlyjs.jl @@ -1,20 +1,12 @@ # https://github.com/spencerlyon2/PlotlyJS.jl -const _plotlyjs_attr = _plotly_attr -const _plotlyjs_seriestype = _plotly_seriestype -const _plotlyjs_style = _plotly_style -const _plotlyjs_marker = _plotly_marker -const _plotlyjs_scale = _plotly_scale - # -------------------------------------------------------------------------------------- function _create_backend_figure(plt::Plot{PlotlyJSBackend}) if !isplotnull() && plt[:overwrite_figure] && isa(current().o, PlotlyJS.SyncPlot) - p = PlotlyJS.plot() - p.window = current().o.window - p + PlotlyJS.SyncPlot(PlotlyJS.Plot(), options = current().o.options) else PlotlyJS.plot() end diff --git a/src/backends/pyplot.jl b/src/backends/pyplot.jl index 4524e967..43211f50 100644 --- a/src/backends/pyplot.jl +++ b/src/backends/pyplot.jl @@ -1,55 +1,9 @@ +# Do "using PyPlot: PyCall, LaTeXStrings" without dependency warning: +const PyCall = PyPlot.PyCall +const LaTeXStrings = PyPlot.LaTeXStrings # https://github.com/stevengj/PyPlot.jl -const _pyplot_attr = merge_with_base_supported([ - :annotations, - :background_color_legend, :background_color_inside, :background_color_outside, - :foreground_color_grid, :foreground_color_legend, :foreground_color_title, - :foreground_color_axis, :foreground_color_border, :foreground_color_guide, :foreground_color_text, - :label, - :linecolor, :linestyle, :linewidth, :linealpha, - :markershape, :markercolor, :markersize, :markeralpha, - :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, - :fillrange, :fillcolor, :fillalpha, - :bins, :bar_width, :bar_edges, :bar_position, - :title, :title_location, :titlefont, - :window_title, - :guide, :guide_position, :lims, :ticks, :scale, :flip, :rotation, - :titlefontfamily, :titlefontsize, :titlefontcolor, - :legendfontfamily, :legendfontsize, :legendfontcolor, - :tickfontfamily, :tickfontsize, :tickfontcolor, - :guidefontfamily, :guidefontsize, :guidefontcolor, - :grid, :gridalpha, :gridstyle, :gridlinewidth, - :legend, :legendtitle, :colorbar, - :marker_z, :line_z, :fill_z, - :levels, - :ribbon, :quiver, :arrow, - :orientation, - :overwrite_figure, - :polar, - :normalize, :weights, - :contours, :aspect_ratio, - :match_dimensions, - :clims, - :inset_subplots, - :dpi, - :colorbar_title, - :stride, - :framestyle, - :tick_direction, - :camera, - :contour_labels, - ]) -const _pyplot_seriestype = [ - :path, :steppre, :steppost, :shape, :straightline, - :scatter, :hexbin, #:histogram2d, :histogram, - # :bar, - :heatmap, :pie, :image, - :contour, :contour3d, :path3d, :scatter3d, :surface, :wireframe - ] -const _pyplot_style = [:auto, :solid, :dash, :dot, :dashdot] -const _pyplot_marker = vcat(_allMarkers, :pixel) -const _pyplot_scale = [:identity, :ln, :log2, :log10] is_marker_supported(::PyPlotBackend, shape::Shape) = true @@ -236,26 +190,22 @@ function add_pyfixedformatter(cbar, vals::AVec) cbar[:update_ticks]() end -@require LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" begin - function labelfunc(scale::Symbol, backend::PyPlotBackend) - if scale == :log10 - x -> LaTeXStrings.latexstring("10^{$x}") - elseif scale == :log2 - x -> LaTeXStrings.latexstring("2^{$x}") - elseif scale == :ln - x -> LaTeXStrings.latexstring("e^{$x}") - else - string - end +function labelfunc(scale::Symbol, backend::PyPlotBackend) + if scale == :log10 + x -> LaTeXStrings.latexstring("10^{$x}") + elseif scale == :log2 + x -> LaTeXStrings.latexstring("2^{$x}") + elseif scale == :ln + x -> LaTeXStrings.latexstring("e^{$x}") + else + string end end -@require PyCall = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0" begin - function py_mask_nans(z) - # pynp["ma"][:masked_invalid](z))) - PyCall.pycall(pynp["ma"][:masked_invalid], Any, z) - # pynp["ma"][:masked_where](pynp["isnan"](z),z) - end +function py_mask_nans(z) + # pynp["ma"][:masked_invalid](z))) + PyCall.pycall(pynp["ma"][:masked_invalid], Any, z) + # pynp["ma"][:masked_where](pynp["isnan"](z),z) end # --------------------------------------------------------------------------- @@ -272,17 +222,6 @@ function fix_xy_lengths!(plt::Plot{PyPlotBackend}, series::Series) end end -# total hack due to PyPlot bug (see issue #145). -# hack: duplicate the color vector when the total rgba fields is the same as the series length -function py_color_fix(c, x) - if (typeof(c) <: AbstractArray && length(c)*4 == length(x)) || - (typeof(c) <: Tuple && length(x) == 4) - vcat(c, c) - else - c - end -end - py_linecolor(series::Series) = py_color(series[:linecolor]) py_markercolor(series::Series) = py_color(series[:markercolor]) py_markerstrokecolor(series::Series) = py_color(series[:markerstrokecolor]) @@ -439,7 +378,11 @@ function py_add_series(plt::Plot{PyPlotBackend}, series::Series) vmin, vmax = clims = get_clims(sp) # Dict to store extra kwargs - extrakw = KW(:vmin => vmin, :vmax => vmax) + if st == :wireframe + extrakw = KW() # vmin, vmax cause an error for wireframe plot + else + extrakw = KW(:vmin => vmin, :vmax => vmax) + end # holds references to any python object representing the matplotlib series handles = [] @@ -547,7 +490,13 @@ function py_add_series(plt::Plot{PyPlotBackend}, series::Series) else py_color(plot_color(series[:markercolor], series[:markeralpha])) end - extrakw[:c] = py_color_fix(markercolor, x) + extrakw[:c] = if markercolor isa Array + permutedims(hcat([[m...] for m in markercolor]...),[2,1]) + elseif markercolor isa Tuple + reshape([markercolor...], 1, length(markercolor)) + else + error("This case is not handled. Please file an issue.") + end xyargs = if st == :bar && !isvertical(series) (y, x) else @@ -555,7 +504,7 @@ function py_add_series(plt::Plot{PyPlotBackend}, series::Series) end if isa(series[:markershape], AbstractVector{Shape}) - # this section will create one scatter per data point to accomodate the + # this section will create one scatter per data point to accommodate the # vector of shapes handle = [] x,y = xyargs @@ -839,7 +788,7 @@ function py_set_ticks(ax, ticks, letter) if ticks == :none || ticks == nothing || ticks == false kw = KW() for dir in (:top,:bottom,:left,:right) - kw[dir] = kw[Symbol(:label,dir)] = "off" + kw[dir] = kw[Symbol(:label,dir)] = false end axis[:set_tick_params](;which="both", kw...) return @@ -1064,7 +1013,7 @@ function _before_layout_calcs(plt::Plot{PyPlotBackend}) ticks = sp[:framestyle] == :none ? nothing : get_ticks(axis) # don't show the 0 tick label for the origin framestyle if sp[:framestyle] == :origin && length(ticks) > 1 - ticks[2][ticks[1] .== 0] = "" + ticks[2][ticks[1] .== 0] .= "" end axis[:ticks] != :native ? py_set_ticks(ax, ticks, letter) : nothing pyaxis[:set_tick_params](direction = axis[:tick_direction] == :out ? "out" : "in") @@ -1102,7 +1051,7 @@ function _before_layout_calcs(plt::Plot{PyPlotBackend}) else ax[:spines][string(dir)][:set_visible](false) end - kw[dir] = kw[Symbol(:label,dir)] = "off" + kw[dir] = kw[Symbol(:label,dir)] = false end ax[:xaxis][:set_tick_params](; which="both", kw...) end @@ -1112,7 +1061,7 @@ function _before_layout_calcs(plt::Plot{PyPlotBackend}) if !ispolar(sp) ax[:spines][string(dir)][:set_visible](false) end - kw[dir] = kw[Symbol(:label,dir)] = "off" + kw[dir] = kw[Symbol(:label,dir)] = false end ax[:yaxis][:set_tick_params](; which="both", kw...) end diff --git a/src/backends/unicodeplots.jl b/src/backends/unicodeplots.jl index afdd08cc..370c9a87 100644 --- a/src/backends/unicodeplots.jl +++ b/src/backends/unicodeplots.jl @@ -1,28 +1,6 @@ # https://github.com/Evizero/UnicodePlots.jl -const _unicodeplots_attr = merge_with_base_supported([ - :label, - :legend, - :seriescolor, - :seriesalpha, - :linestyle, - :markershape, - :bins, - :title, - :guide, :lims, - ]) -const _unicodeplots_seriestype = [ - :path, :scatter, :straightline, - # :bar, - :shape, - :histogram2d, - :spy -] -const _unicodeplots_style = [:auto, :solid] -const _unicodeplots_marker = [:none, :auto, :circle] -const _unicodeplots_scale = [:identity] - # don't warn on unsupported... there's just too many warnings!! warnOnUnsupported_args(::UnicodePlotsBackend, plotattributes::KW) = nothing diff --git a/src/backends/web.jl b/src/backends/web.jl index 55984167..b1663435 100644 --- a/src/backends/web.jl +++ b/src/backends/web.jl @@ -42,8 +42,14 @@ function write_temp_html(plt::AbstractPlot) end function standalone_html_window(plt::AbstractPlot) + old = use_local_dependencies[] # save state to restore afterwards + # if we open a browser ourself, we can host local files, so + # when we have a local plotly downloaded this is the way to go! + use_local_dependencies[] = isfile(plotly_local_file_path) filename = write_temp_html(plt) open_browser_window(filename) + # restore for other backends + use_local_dependencies[] = old end # uses wkhtmltopdf/wkhtmltoimage: http://wkhtmltopdf.org/downloads.html diff --git a/src/components.jl b/src/components.jl index 8a35c95c..46fc0f7d 100644 --- a/src/components.jl +++ b/src/components.jl @@ -1,7 +1,7 @@ -const P2 = FixedSizeArrays.Vec{2,Float64} -const P3 = FixedSizeArrays.Vec{3,Float64} +const P2 = StaticArrays.SVector{2,Float64} +const P3 = StaticArrays.SVector{3,Float64} nanpush!(a::AbstractVector{P2}, b) = (push!(a, P2(NaN,NaN)); push!(a, b)) nanappend!(a::AbstractVector{P2}, b) = (push!(a, P2(NaN,NaN)); append!(a, b)) @@ -491,7 +491,7 @@ function series_annotations_shapes!(series::Series, scaletype::Symbol = :pixels) # with a list of custom shapes for each msw,msh = anns.scalefactor msize = Float64[] - shapes = Vector{Shape}(length(anns.strs)) + shapes = Vector{Shape}(undef, length(anns.strs)) for i in eachindex(anns.strs) str = _cycle(anns.strs,i) @@ -509,7 +509,7 @@ function series_annotations_shapes!(series::Series, scaletype::Symbol = :pixels) # and then re-scale a copy of baseshape to match the w/h ratio maxscale = max(xscale, yscale) push!(msize, maxscale) - baseshape = _cycle(get(anns.baseshape),i) + baseshape = _cycle(anns.baseshape, i) shapes[i] = scale(baseshape, msw*xscale/maxscale, msh*yscale/maxscale, (0,0)) end series[:markershape] = shapes @@ -736,7 +736,7 @@ end # ----------------------------------------------------------------------- "create a BezierCurve for plotting" -mutable struct BezierCurve{T <: FixedSizeArrays.Vec} +mutable struct BezierCurve{T <: StaticArrays.SVector} control_points::Vector{T} end @@ -750,7 +750,7 @@ function (bc::BezierCurve)(t::Real) end # mean(x::Real, y::Real) = 0.5*(x+y) #commented out as I cannot see this used anywhere and it overwrites a Base method with different functionality -# mean{N,T<:Real}(ps::FixedSizeArrays.Vec{N,T}...) = sum(ps) / length(ps) # I also could not see this used anywhere, and it's type piracy - implementing a NaNMath version for this would just involve converting to a standard array +# mean{N,T<:Real}(ps::StaticArrays.SVector{N,T}...) = sum(ps) / length(ps) # I also could not see this used anywhere, and it's type piracy - implementing a NaNMath version for this would just involve converting to a standard array @deprecate curve_points coords diff --git a/src/deprecated/backends/bokeh.jl b/src/deprecated/backends/bokeh.jl deleted file mode 100644 index 9e906b75..00000000 --- a/src/deprecated/backends/bokeh.jl +++ /dev/null @@ -1,208 +0,0 @@ - -# https://github.com/bokeh/Bokeh.jl - - -supported_attrs(::BokehBackend) = merge_with_base_supported([ - # :annotations, - # :axis, - # :background_color, - :linecolor, - # :color_palette, - # :fillrange, - # :fillcolor, - # :fillalpha, - # :foreground_color, - :group, - # :label, - # :layout, - # :legend, - :seriescolor, :seriesalpha, - :linestyle, - :seriestype, - :linewidth, - # :linealpha, - :markershape, - :markercolor, - :markersize, - # :markeralpha, - # :markerstrokewidth, - # :markerstrokecolor, - # :markerstrokestyle, - # :n, - # :bins, - # :nc, - # :nr, - # :pos, - # :smooth, - # :show, - :size, - :title, - # :window_title, - :x, - # :xguide, - # :xlims, - # :xticks, - :y, - # :yguide, - # :ylims, - # :yrightlabel, - # :yticks, - # :xscale, - # :yscale, - # :xflip, - # :yflip, - # :z, - # :tickfont, - # :guidefont, - # :legendfont, - # :grid, - # :surface, - # :levels, - ]) -supported_types(::BokehBackend) = [:path, :scatter] -supported_styles(::BokehBackend) = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot] -supported_markers(::BokehBackend) = [:none, :auto, :circle, :rect, :diamond, :utriangle, :dtriangle, :cross, :xcross, :star5] -supported_scales(::BokehBackend) = [:identity, :ln] -is_subplot_supported(::BokehBackend) = false - - -# -------------------------------------------------------------------------------------- - - - -function _initialize_backend(::BokehBackend; kw...) - @eval begin - @warn("Bokeh is no longer supported... many features will likely be broken.") - import Bokeh - export Bokeh - end -end - - -const _glyphtypes = KW( - :circle => :Circle, - :rect => :Square, - :diamond => :Diamond, - :utriangle => :Triangle, - :dtriangle => :InvertedTriangle, - # :pentagon => - # :hexagon => - # :heptagon => - # :octagon => - :cross => :Cross, - :xcross => :X, - :star5 => :Asterisk, - ) - - -function bokeh_glyph_type(plotattributes::KW) - st = plotattributes[:seriestype] - mt = plotattributes[:markershape] - if st == :scatter && mt == :none - mt = :circle - end - - # if we have a marker, use that - if st == :scatter || mt != :none - return _glyphtypes[mt] - end - - # otherwise return a line - return :Line -end - -function get_stroke_vector(linestyle::Symbol) - dash = 12 - dot = 3 - gap = 2 - linestyle == :solid && return Int[] - linestyle == :dash && return Int[dash, gap] - linestyle == :dot && return Int[dot, gap] - linestyle == :dashdot && return Int[dash, gap, dot, gap] - linestyle == :dashdotdot && return Int[dash, gap, dot, gap, dot, gap] - error("unsupported linestyle: ", linestyle) -end - -# --------------------------------------------------------------------------- - -# function _create_plot(pkg::BokehBackend, plotattributes::KW) -function _create_backend_figure(plt::Plot{BokehBackend}) - # TODO: create the window/canvas/context that is the plot within the backend (call it `o`) - # TODO: initialize the plot... title, xlabel, bgcolor, etc - - datacolumns = Bokeh.BokehDataSet[] - tools = Bokeh.tools() - filename = tempname() * ".html" - title = plt.attr[:title] - w, h = plt.attr[:size] - xaxis_type = plt.attr[:xscale] == :log10 ? :log : :auto - yaxis_type = plt.attr[:yscale] == :log10 ? :log : :auto - # legend = plt.attr[:legend] ? xxxx : nothing - legend = nothing - extra_args = KW() # TODO: we'll put extra settings (xlim, etc) here - Bokeh.Plot(datacolumns, tools, filename, title, w, h, xaxis_type, yaxis_type, legend) #, extra_args) - - # Plot(bplt, pkg, 0, plotattributes, KW[]) -end - - -# function _series_added(::BokehBackend, plt::Plot, plotattributes::KW) -function _series_added(plt::Plot{BokehBackend}, series::Series) - bdata = Dict{Symbol, Vector}(:x => collect(series.plotattributes[:x]), :y => collect(series.plotattributes[:y])) - - glyph = Bokeh.Bokehjs.Glyph( - glyphtype = bokeh_glyph_type(plotattributes), - linecolor = webcolor(plotattributes[:linecolor]), # shape's stroke or line color - linewidth = plotattributes[:linewidth], # shape's stroke width or line width - fillcolor = webcolor(plotattributes[:markercolor]), - size = ceil(Int, plotattributes[:markersize] * 2.5), # magic number 2.5 to keep in same scale as other backends - dash = get_stroke_vector(plotattributes[:linestyle]) - ) - - legend = nothing # TODO - push!(plt.o.datacolumns, Bokeh.BokehDataSet(bdata, glyph, legend)) - - # push!(plt.seriesargs, plotattributes) - # plt -end - -# ---------------------------------------------------------------- - -# TODO: override this to update plot items (title, xlabel, etc) after creation -function _update_plot_object(plt::Plot{BokehBackend}, plotattributes::KW) -end - -# ---------------------------------------------------------------- - -# accessors for x/y data - -# function getxy(plt::Plot{BokehBackend}, i::Int) -# series = plt.o.datacolumns[i].data -# series[:x], series[:y] -# end -# -# function setxy!(plt::Plot{BokehBackend}, xy::Tuple{X,Y}, i::Integer) -# series = plt.o.datacolumns[i].data -# series[:x], series[:y] = xy -# plt -# end - - - -# ---------------------------------------------------------------- - - -# ---------------------------------------------------------------- - -function Base.show(io::IO, ::MIME"image/png", plt::AbstractPlot{BokehBackend}) - # TODO: write a png to io - @warn("mime png not implemented") -end - -function Base.display(::PlotsDisplay, plt::Plot{BokehBackend}) - Bokeh.showplot(plt.o) -end - -# function Base.display(::PlotsDisplay, plt::Subplot{BokehBackend}) -# # TODO: display/show the subplot -# end diff --git a/src/deprecated/backends/gadfly.jl b/src/deprecated/backends/gadfly.jl deleted file mode 100644 index 37dac678..00000000 --- a/src/deprecated/backends/gadfly.jl +++ /dev/null @@ -1,744 +0,0 @@ - -# https://github.com/dcjones/Gadfly.jl - - -supported_attrs(::GadflyBackend) = merge_with_base_supported([ - :annotations, - :background_color, :foreground_color, :color_palette, - :group, :label, :seriestype, - :seriescolor, :seriesalpha, - :linecolor, :linestyle, :linewidth, :linealpha, - :markershape, :markercolor, :markersize, :markeralpha, - :markerstrokewidth, :markerstrokecolor, :markerstrokealpha, - :fillrange, :fillcolor, :fillalpha, - :bins, :n, :nc, :nr, :layout, :smooth, - :title, :window_title, :show, :size, - :x, :xguide, :xlims, :xticks, :xscale, :xflip, - :y, :yguide, :ylims, :yticks, :yscale, :yflip, - :z, - :tickfont, :guidefont, :legendfont, - :grid, :legend, :colorbar, - :marker_z, :levels, - :xerror, :yerror, - :ribbon, :quiver, - :orientation, - ]) -supported_types(::GadflyBackend) = [ - :path, - :scatter, :hexbin, - :bar, - :contour, :shape - ] -supported_styles(::GadflyBackend) = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot] -supported_markers(::GadflyBackend) = vcat(_allMarkers, Shape) -supported_scales(::GadflyBackend) = [:identity, :ln, :log2, :log10, :asinh, :sqrt] -is_subplot_supported(::GadflyBackend) = true - - -# -------------------------------------------------------------------------------------- - -function _initialize_backend(::GadflyBackend; kw...) - @eval begin - import Gadfly, Compose - export Gadfly, Compose - include(joinpath(dirname(@__FILE__), "gadfly_shapes.jl")) - end -end - -# --------------------------------------------------------------------------- - -# immutable MissingVec <: AbstractVector{Float64} end -# Base.size(v::MissingVec) = (1,) -# Base.getindex(v::MissingVec, i::Integer) = 0.0 - -function createGadflyPlotObject(plotattributes::KW) - gplt = Gadfly.Plot() - gplt.mapping = Dict() - gplt.data_source = Gadfly.DataFrames.DataFrame() - # gplt.layers = gplt.layers[1:0] - gplt.layers = [Gadfly.layer(Gadfly.Geom.point(tag=:remove), x=zeros(1), y=zeros(1));] # x=MissingVec(), y=MissingVec());] - gplt.guides = Gadfly.GuideElement[Gadfly.Guide.xlabel(plotattributes[:xguide]), - Gadfly.Guide.ylabel(plotattributes[:yguide]), - Gadfly.Guide.title(plotattributes[:title])] - gplt -end - -# --------------------------------------------------------------------------- - - -function getLineGeom(plotattributes::KW) - st = plotattributes[:seriestype] - xbins, ybins = maketuple(plotattributes[:bins]) - if st == :hexb - Gadfly.Geom.hexbin(xbincount = xbins, ybincount = ybins) - elseif st == :histogram2d - Gadfly.Geom.histogram2d(xbincount = xbins, ybincount = ybins) - elseif st == :histogram - Gadfly.Geom.histogram(bincount = xbins, - orientation = isvertical(plotattributes) ? :vertical : :horizontal, - position = plotattributes[:bar_position] == :stack ? :stack : :dodge) - elseif st == :path - Gadfly.Geom.path - elseif st in (:bar, :sticks) - Gadfly.Geom.bar - elseif st == :steppost - Gadfly.Geom.step - elseif st == :steppre - Gadfly.Geom.step(direction = :vh) - elseif st == :hline - Gadfly.Geom.hline - elseif st == :vline - Gadfly.Geom.vline - elseif st == :contour - Gadfly.Geom.contour(levels = plotattributes[:levels]) - # elseif st == :shape - # Gadfly.Geom.polygon(fill = true, preserve_order = true) - else - nothing - end -end - -function get_extra_theme_args(plotattributes::KW, k::Symbol) - # gracefully handles old Gadfly versions - extra_theme_args = KW() - try - extra_theme_args[:line_style] = Gadfly.get_stroke_vector(plotattributes[k]) - catch err - if string(err) == "UndefVarError(:get_stroke_vector)" - Base.warn_once("Gadfly.get_stroke_vector failed... do you have an old version of Gadfly?") - else - rethrow() - end - end - extra_theme_args -end - -function getGadflyLineTheme(plotattributes::KW) - st = plotattributes[:seriestype] - lc = convertColor(getColor(plotattributes[:linecolor]), plotattributes[:linealpha]) - fc = convertColor(getColor(plotattributes[:fillcolor]), plotattributes[:fillalpha]) - - Gadfly.Theme(; - default_color = (st in (:histogram,:histogram2d,:hexbin,:bar,:sticks) ? fc : lc), - line_width = (st == :sticks ? 1 : plotattributes[:linewidth]) * Gadfly.px, - # line_style = Gadfly.get_stroke_vector(plotattributes[:linestyle]), - lowlight_color = x->RGB(fc), # fill/ribbon - lowlight_opacity = alpha(fc), # fill/ribbon - bar_highlight = RGB(lc), # bars - get_extra_theme_args(plotattributes, :linestyle)... - ) -end - -# add a line as a new layer -function addGadflyLine!(plt::Plot, numlayers::Int, plotattributes::KW, geoms...) - gplt = getGadflyContext(plt) - gfargs = vcat(geoms..., getGadflyLineTheme(plotattributes)) - kwargs = KW() - st = plotattributes[:seriestype] - - # add a fill? - if plotattributes[:fillrange] != nothing && st != :contour - fillmin, fillmax = map(makevec, maketuple(plotattributes[:fillrange])) - nmin, nmax = length(fillmin), length(fillmax) - kwargs[:ymin] = Float64[min(y, fillmin[mod1(i, nmin)], fillmax[mod1(i, nmax)]) for (i,y) in enumerate(plotattributes[:y])] - kwargs[:ymax] = Float64[max(y, fillmin[mod1(i, nmin)], fillmax[mod1(i, nmax)]) for (i,y) in enumerate(plotattributes[:y])] - push!(gfargs, Gadfly.Geom.ribbon) - end - - if st in (:hline, :vline) - kwargs[st == :hline ? :yintercept : :xintercept] = plotattributes[:y] - - else - if st == :sticks - w = 0.01 * mean(diff(plotattributes[:x])) - kwargs[:xmin] = plotattributes[:x] - w - kwargs[:xmax] = plotattributes[:x] + w - elseif st == :contour - kwargs[:z] = plotattributes[:z].surf - addGadflyContColorScale(plt, plotattributes[:linecolor]) - end - - kwargs[:x] = plotattributes[st == :histogram ? :y : :x] - kwargs[:y] = plotattributes[:y] - - end - - # # add the layer - Gadfly.layer(gfargs...; order=numlayers, kwargs...) -end - - -# --------------------------------------------------------------------------- - -get_shape(sym::Symbol) = _shapes[sym] -get_shape(shape::Shape) = shape - -# extract the underlying ShapeGeometry object(s) -getMarkerGeom(shapes::AVec) = gadflyshape(map(get_shape, shapes)) -getMarkerGeom(other) = gadflyshape(get_shape(other)) - -# getMarkerGeom(shape::Shape) = gadflyshape(shape) -# getMarkerGeom(shape::Symbol) = gadflyshape(_shapes[shape]) -# getMarkerGeom(shapes::AVec) = gadflyshape(map(gadflyshape, shapes)) # map(getMarkerGeom, shapes) -function getMarkerGeom(plotattributes::KW) - if plotattributes[:seriestype] == :shape - Gadfly.Geom.polygon(fill = true, preserve_order = true) - else - getMarkerGeom(plotattributes[:markershape]) - end -end - -function getGadflyMarkerTheme(plotattributes::KW, attr::KW) - c = getColor(plotattributes[:markercolor]) - α = plotattributes[:markeralpha] - if α != nothing - c = RGBA(RGB(c), α) - end - - ms = plotattributes[:markersize] - ms = if typeof(ms) <: AVec - @warn("Gadfly doesn't support variable marker sizes... using the average: $(mean(ms))") - mean(ms) * Gadfly.px - else - ms * Gadfly.px - end - - Gadfly.Theme(; - default_color = c, - default_point_size = ms, - discrete_highlight_color = c -> RGB(getColor(plotattributes[:markerstrokecolor])), - highlight_width = plotattributes[:markerstrokewidth] * Gadfly.px, - line_width = plotattributes[:markerstrokewidth] * Gadfly.px, - # get_extra_theme_args(plotattributes, :markerstrokestyle)... - ) -end - -function addGadflyContColorScale(plt::Plot{GadflyBackend}, c) - plt.attr[:colorbar] == :none && return - if !isa(c, ColorGradient) - c = default_gradient() - end - push!(getGadflyContext(plt).scales, Gadfly.Scale.ContinuousColorScale(p -> RGB(getColorZ(c, p)))) -end - -function addGadflyMarker!(plt::Plot, numlayers::Int, plotattributes::KW, attr::KW, geoms...) - gfargs = vcat(geoms..., getGadflyMarkerTheme(plotattributes, attr), getMarkerGeom(plotattributes)) - kwargs = KW() - - # handle continuous color scales for the markers - zcolor = plotattributes[:marker_z] - if zcolor != nothing && typeof(zcolor) <: AVec - kwargs[:color] = zcolor - addGadflyContColorScale(plt, plotattributes[:markercolor]) - end - - Gadfly.layer(gfargs...; x = plotattributes[:x], y = plotattributes[:y], order=numlayers, kwargs...) -end - - -# --------------------------------------------------------------------------- - -function addToGadflyLegend(plt::Plot, plotattributes::KW) - if plt.attr[:legend] != :none && plotattributes[:label] != "" - gplt = getGadflyContext(plt) - - # add the legend if needed - if all(g -> !isa(g, Gadfly.Guide.ManualColorKey), gplt.guides) - pushfirst!(gplt.guides, Gadfly.Guide.manual_color_key("", AbstractString[], Color[])) - end - - # now add the series to the legend - for guide in gplt.guides - if isa(guide, Gadfly.Guide.ManualColorKey) - # TODO: there's a BUG in gadfly if you pass in the same color more than once, - # since gadfly will call unique(colors), but doesn't also merge the rows that match - # Should ensure from this side that colors which are the same are merged together - - c = getColor(plotattributes[plotattributes[:markershape] == :none ? :linecolor : :markercolor]) - foundit = false - - # extend the label if we found this color - for i in 1:length(guide.colors) - if RGB(c) == guide.colors[i] - guide.labels[i] *= ", " * plotattributes[:label] - foundit = true - end - end - - # didn't find the color, so add a new entry into the legend - if !foundit - push!(guide.labels, plotattributes[:label]) - push!(guide.colors, c) - end - end - end - end -end - -getGadflySmoothing(smooth::Bool) = smooth ? [Gadfly.Geom.smooth(method=:lm)] : Any[] -getGadflySmoothing(smooth::Real) = [Gadfly.Geom.smooth(method=:loess, smoothing=float(smooth))] - - -function addGadflySeries!(plt::Plot, plotattributes::KW) - layers = Gadfly.Layer[] - gplt = getGadflyContext(plt) - - # add a regression line? - # TODO: make more flexible - smooth = getGadflySmoothing(plotattributes[:smooth]) - - # lines - geom = getLineGeom(plotattributes) - if geom != nothing - prepend!(layers, addGadflyLine!(plt, length(gplt.layers), plotattributes, geom, smooth...)) - smooth = Any[] # don't add a regression for markers too - end - - # special handling for ohlc and scatter - st = plotattributes[:seriestype] - # if st == :ohlc - # error("Haven't re-implemented after refactoring") - if st in (:histogram2d, :hexbin) && (isa(plotattributes[:fillcolor], ColorGradient) || isa(plotattributes[:fillcolor], ColorFunction)) - push!(gplt.scales, Gadfly.Scale.ContinuousColorScale(p -> RGB(getColorZ(plotattributes[:fillcolor], p)))) - elseif st == :scatter && plotattributes[:markershape] == :none - plotattributes[:markershape] = :circle - end - - # markers - if plotattributes[:markershape] != :none || st == :shape - prepend!(layers, addGadflyMarker!(plt, length(gplt.layers), plotattributes, plt.attr, smooth...)) - end - - st in (:histogram2d, :hexbin, :contour) || addToGadflyLegend(plt, plotattributes) - - # now save the layers that apply to this series - plotattributes[:gadflylayers] = layers - prepend!(gplt.layers, layers) -end - - -# --------------------------------------------------------------------------- - -# NOTE: I'm leaving this here and commented out just in case I want to implement again... it was hacky code to create multi-colored line segments - -# # colorgroup -# z = plotattributes[:z] - -# # handle line segments of different colors -# cscheme = plotattributes[:linecolor] -# if isa(cscheme, ColorVector) -# # create a color scale, and set the color group to the index of the color -# push!(gplt.scales, Gadfly.Scale.color_discrete_manual(cscheme.v...)) - -# # this is super weird, but... oh well... for some reason this creates n separate line segments... -# # create a list of vertices that go: [x1,x2,x2,x3,x3, ... ,xi,xi, ... xn,xn] (same for y) -# # then the vector passed to the "color" keyword should be a vector: [1,1,2,2,3,3,4,4, ..., i,i, ... , n,n] -# csindices = Int[mod1(i,length(cscheme.v)) for i in 1:length(plotattributes[:y])] -# cs = collect(repeat(csindices', 2, 1))[1:end-1] -# grp = collect(repeat((1:length(plotattributes[:y]))', 2, 1))[1:end-1] -# plotattributes[:x], plotattributes[:y] = map(createSegments, (plotattributes[:x], plotattributes[:y])) -# colorgroup = [(:linecolor, cs), (:group, grp)] - - -# --------------------------------------------------------------------------- - - -function addGadflyTicksGuide(gplt, ticks, isx::Bool) - ticks == :auto && return - - # remove the ticks? - if ticks in (:none, false, nothing) - return addOrReplace(gplt.guides, isx ? Gadfly.Guide.xticks : Gadfly.Guide.yticks; label=false) - end - - ttype = ticksType(ticks) - - # just the values... put ticks here, but use standard labels - if ttype == :ticks - gtype = isx ? Gadfly.Guide.xticks : Gadfly.Guide.yticks - replaceType(gplt.guides, gtype(ticks = collect(ticks))) - - # set the ticks and the labels - # Note: this is pretty convoluted, but I think it works. We set the ticks using Gadfly.Guide, - # and then set the label function (wraps a dict lookup) through a continuous Gadfly.Scale. - elseif ttype == :ticks_and_labels - gtype = isx ? Gadfly.Guide.xticks : Gadfly.Guide.yticks - replaceType(gplt.guides, gtype(ticks = collect(ticks[1]))) - - # # TODO add xtick_label function (given tick, return label??) - # # Scale.x_discrete(; labels=nothing, levels=nothing, order=nothing) - # filterGadflyScale(gplt, isx) - # gfunc = isx ? Gadfly.Scale.x_discrete : Gadfly.Scale.y_discrete - # labelmap = Dict(zip(ticks...)) - # labelfunc = val -> labelmap[val] - # push!(gplt.scales, gfunc(levels = collect(ticks[1]), labels = labelfunc)) - - filterGadflyScale(gplt, isx) - gfunc = isx ? Gadfly.Scale.x_continuous : Gadfly.Scale.y_continuous - labelmap = Dict(zip(ticks...)) - labelfunc = val -> labelmap[val] - push!(gplt.scales, gfunc(labels = labelfunc)) - - else - error("Invalid input for $(isx ? "xticks" : "yticks"): ", ticks) - end -end - -continuousAndSameAxis(scale, isx::Bool) = isa(scale, Gadfly.Scale.ContinuousScale) && scale.vars[1] == (isx ? :x : :y) -filterGadflyScale(gplt, isx::Bool) = filter!(scale -> !continuousAndSameAxis(scale, isx), gplt.scales) - - -function getGadflyScaleFunction(plotattributes::KW, isx::Bool) - scalekey = isx ? :xscale : :yscale - hasScaleKey = haskey(plotattributes, scalekey) - if hasScaleKey - scale = plotattributes[scalekey] - scale == :ln && return isx ? Gadfly.Scale.x_log : Gadfly.Scale.y_log, hasScaleKey, log - scale == :log2 && return isx ? Gadfly.Scale.x_log2 : Gadfly.Scale.y_log2, hasScaleKey, log2 - scale == :log10 && return isx ? Gadfly.Scale.x_log10 : Gadfly.Scale.y_log10, hasScaleKey, log10 - scale == :asinh && return isx ? Gadfly.Scale.x_asinh : Gadfly.Scale.y_asinh, hasScaleKey, asinh - scale == :sqrt && return isx ? Gadfly.Scale.x_sqrt : Gadfly.Scale.y_sqrt, hasScaleKey, sqrt - end - isx ? Gadfly.Scale.x_continuous : Gadfly.Scale.y_continuous, hasScaleKey, identity -end - - -function addGadflyLimitsScale(gplt, plotattributes::KW, isx::Bool) - gfunc, hasScaleKey, func = getGadflyScaleFunction(plotattributes, isx) - - # do we want to add min/max limits for the axis? - limsym = isx ? :xlims : :ylims - limargs = Any[] - - # map :auto to nothing, otherwise add to limargs - lims = get(plotattributes, limsym, :auto) - if lims == :auto - lims = nothing - else - if limsType(lims) == :limits - push!(limargs, (:minvalue, min(lims...))) - push!(limargs, (:maxvalue, max(lims...))) - else - error("Invalid input for $(isx ? "xlims" : "ylims"): ", lims) - end - end - - # replace any current scales with this one - if hasScaleKey || !isempty(limargs) - filterGadflyScale(gplt, isx) - push!(gplt.scales, gfunc(; limargs...)) - end - - lims, func -end - -function updateGadflyAxisFlips(gplt, plotattributes::KW, xlims, ylims, xfunc, yfunc) - if isa(gplt.coord, Gadfly.Coord.Cartesian) - gplt.coord = Gadfly.Coord.cartesian( - gplt.coord.xvars, - gplt.coord.yvars; - xmin = xlims == nothing ? gplt.coord.xmin : xfunc(minimum(xlims)), - xmax = xlims == nothing ? gplt.coord.xmax : xfunc(maximum(xlims)), - ymin = ylims == nothing ? gplt.coord.ymin : yfunc(minimum(ylims)), - ymax = ylims == nothing ? gplt.coord.ymax : yfunc(maximum(ylims)), - xflip = get(plotattributes, :xflip, gplt.coord.xflip), - yflip = get(plotattributes, :yflip, gplt.coord.yflip), - fixed = gplt.coord.fixed, - aspect_ratio = gplt.coord.aspect_ratio, - raster = gplt.coord.raster - ) - else - gplt.coord = Gadfly.Coord.Cartesian( - xflip = get(plotattributes, :xflip, false), - yflip = get(plotattributes, :yflip, false) - ) - end -end - - -function findGuideAndSet(gplt, t::DataType, args...; kw...) - for (i,guide) in enumerate(gplt.guides) - if isa(guide, t) - gplt.guides[i] = t(args...; kw...) - end - end -end - -function updateGadflyGuides(plt::Plot, plotattributes::KW) - gplt = getGadflyContext(plt) - haskey(plotattributes, :title) && findGuideAndSet(gplt, Gadfly.Guide.title, string(plotattributes[:title])) - haskey(plotattributes, :xguide) && findGuideAndSet(gplt, Gadfly.Guide.xlabel, string(plotattributes[:xguide])) - haskey(plotattributes, :yguide) && findGuideAndSet(gplt, Gadfly.Guide.ylabel, string(plotattributes[:yguide])) - - xlims, xfunc = addGadflyLimitsScale(gplt, plotattributes, true) - ylims, yfunc = addGadflyLimitsScale(gplt, plotattributes, false) - - ticks = get(plotattributes, :xticks, :auto) - if ticks == :none - _remove_axis(plt, true) - else - addGadflyTicksGuide(gplt, ticks, true) - end - ticks = get(plotattributes, :yticks, :auto) - if ticks == :none - _remove_axis(plt, false) - else - addGadflyTicksGuide(gplt, ticks, false) - end - - updateGadflyAxisFlips(gplt, plotattributes, xlims, ylims, xfunc, yfunc) -end - -function updateGadflyPlotTheme(plt::Plot, plotattributes::KW) - kwargs = KW() - - # colors - insidecolor, gridcolor, textcolor, guidecolor, legendcolor = - map(s -> getColor(plotattributes[s]), ( - :background_color_inside, - :foreground_color_grid, - :foreground_color_text, - :foreground_color_guide, - :foreground_color_legend - )) - - # # hide the legend? - leg = plotattributes[plotattributes[:legend] == :none ? :colorbar : :legend] - if leg != :best - kwargs[:key_position] = leg == :inside ? :right : leg - end - - if !get(plotattributes, :grid, true) - kwargs[:grid_color] = gridcolor - end - - # fonts - tfont, gfont, lfont = plotattributes[:tickfont], plotattributes[:guidefont], plotattributes[:legendfont] - - getGadflyContext(plt).theme = Gadfly.Theme(; - background_color = insidecolor, - minor_label_color = textcolor, - minor_label_font = tfont.family, - minor_label_font_size = tfont.pointsize * Gadfly.pt, - major_label_color = guidecolor, - major_label_font = gfont.family, - major_label_font_size = gfont.pointsize * Gadfly.pt, - key_title_color = guidecolor, - key_title_font = gfont.family, - key_title_font_size = gfont.pointsize * Gadfly.pt, - key_label_color = legendcolor, - key_label_font = lfont.family, - key_label_font_size = lfont.pointsize * Gadfly.pt, - plot_padding = 1 * Gadfly.mm, - kwargs... - ) -end - -# ---------------------------------------------------------------- - - -function createGadflyAnnotationObject(x, y, val::AbstractString) - Gadfly.Guide.annotation(Compose.compose( - Compose.context(), - Compose.text(x, y, val) - )) -end - -function createGadflyAnnotationObject(x, y, txt::PlotText) - halign = (txt.font.halign == :hcenter ? Compose.hcenter : (txt.font.halign == :left ? Compose.hleft : Compose.hright)) - valign = (txt.font.valign == :vcenter ? Compose.vcenter : (txt.font.valign == :top ? Compose.vtop : Compose.vbottom)) - rotations = (txt.font.rotation == 0.0 ? [] : [Compose.Rotation(txt.font.rotation, Compose.Point(Compose.x_measure(x), Compose.y_measure(y)))]) - Gadfly.Guide.annotation(Compose.compose( - Compose.context(), - Compose.text(x, y, txt.str, halign, valign, rotations...), - Compose.font(string(txt.font.family)), - Compose.fontsize(txt.font.pointsize * Gadfly.pt), - Compose.stroke(txt.font.color), - Compose.fill(txt.font.color) - )) -end - -function _add_annotations(plt::Plot{GadflyBackend}, anns::AVec{Tuple{X,Y,V}}) where {X,Y,V} - for ann in anns - push!(plt.o.guides, createGadflyAnnotationObject(ann...)) - end -end - - -# --------------------------------------------------------------------------- - -# create a blank Gadfly.Plot object -# function _create_plot(pkg::GadflyBackend, plotattributes::KW) -# gplt = createGadflyPlotObject(plotattributes) -# Plot(gplt, pkg, 0, plotattributes, KW[]) -# end -function _create_backend_figure(plt::Plot{GadflyBackend}) - createGadflyPlotObject(plt.attr) -end - - -# plot one data series -# function _series_added(::GadflyBackend, plt::Plot, plotattributes::KW) -function _series_added(plt::Plot{GadflyBackend}, series::Series) - # first clear out the temporary layer - gplt = getGadflyContext(plt) - if gplt.layers[1].geom.tag == :remove - gplt.layers = gplt.layers[2:end] - end - - addGadflySeries!(plt, series.plotattributes) - # push!(plt.seriesargs, plotattributes) - # plt -end - - - -function _update_plot_object(plt::Plot{GadflyBackend}, plotattributes::KW) - updateGadflyGuides(plt, plotattributes) - updateGadflyPlotTheme(plt, plotattributes) -end - - -# ---------------------------------------------------------------- - -# accessors for x/y data - -# TODO: need to save all the layer indices which apply to this series -function getGadflyMappings(plt::Plot, i::Integer) - @assert i > 0 && i <= plt.n - mappings = [l.mapping for l in plt.seriesargs[i][:gadflylayers]] -end - -function getxy(plt::Plot{GadflyBackend}, i::Integer) - mapping = getGadflyMappings(plt, i)[1] - mapping[:x], mapping[:y] -end - -function setxy!(plt::Plot{GadflyBackend}, xy::Tuple{X,Y}, i::Integer) where {X,Y} - for mapping in getGadflyMappings(plt, i) - mapping[:x], mapping[:y] = xy - end - plt -end - -# ---------------------------------------------------------------- - - -# # create the underlying object (each backend will do this differently) -# function _create_subplot(subplt::Subplot{GadflyBackend}, isbefore::Bool) -# isbefore && return false # wait until after plotting to create the subplots -# subplt.o = nothing -# true -# end - - -function _remove_axis(plt::Plot{GadflyBackend}, isx::Bool) - gplt = getGadflyContext(plt) - addOrReplace(gplt.guides, isx ? Gadfly.Guide.xticks : Gadfly.Guide.yticks; label=false) - addOrReplace(gplt.guides, isx ? Gadfly.Guide.xlabel : Gadfly.Guide.ylabel, "") -end - -function _expand_limits(lims, plt::Plot{GadflyBackend}, isx::Bool) - for l in getGadflyContext(plt).layers - _expand_limits(lims, l.mapping[isx ? :x : :y]) - end -end - - -# ---------------------------------------------------------------- - - -getGadflyContext(plt::Plot{GadflyBackend}) = plt.o -# getGadflyContext(subplt::Subplot{GadflyBackend}) = buildGadflySubplotContext(subplt) - -# # create my Compose.Context grid by hstacking and vstacking the Gadfly.Plot objects -# function buildGadflySubplotContext(subplt::Subplot) -# rows = Any[] -# row = Any[] -# for (i,(r,c)) in enumerate(subplt.layout) -# -# # add the Plot object to the row -# push!(row, getGadflyContext(subplt.plts[i])) -# -# # add the row -# if c == ncols(subplt.layout, r) -# push!(rows, Gadfly.hstack(row...)) -# row = Any[] -# end -# end -# -# # stack the rows -# Gadfly.vstack(rows...) -# end - -setGadflyDisplaySize(w,h) = Compose.set_default_graphic_size(w * Compose.px, h * Compose.px) -setGadflyDisplaySize(plt::Plot) = setGadflyDisplaySize(plt.attr[:size]...) -# setGadflyDisplaySize(subplt::Subplot) = setGadflyDisplaySize(getattr(subplt, 1)[:size]...) -# ------------------------------------------------------------------------- - - -function doshow(io::IO, func, plt::AbstractPlot{P}) where P<:Union{GadflyBackend,ImmerseBackend} - gplt = getGadflyContext(plt) - setGadflyDisplaySize(plt) - Gadfly.draw(func(io, Compose.default_graphic_width, Compose.default_graphic_height), gplt) -end - -getGadflyWriteFunc(::MIME"image/png") = Gadfly.PNG -getGadflyWriteFunc(::MIME"image/svg+xml") = Gadfly.SVG -# getGadflyWriteFunc(::MIME"text/html") = Gadfly.SVGJS -getGadflyWriteFunc(::MIME"application/pdf") = Gadfly.PDF -getGadflyWriteFunc(::MIME"application/postscript") = Gadfly.PS -getGadflyWriteFunc(::MIME"application/x-tex") = Gadfly.PGF -getGadflyWriteFunc(m::MIME) = error("Unsupported in Gadfly/Immerse: ", m) - -for mime in (MIME"image/png", MIME"image/svg+xml", MIME"application/pdf", MIME"application/postscript", MIME"application/x-tex") - @eval function Base.show(io::IO, ::$mime, plt::AbstractPlot{P}) where P<:Union{GadflyBackend,ImmerseBackend} - func = getGadflyWriteFunc($mime()) - doshow(io, func, plt) - end -end - - - -function Base.display(::PlotsDisplay, plt::Plot{GadflyBackend}) - setGadflyDisplaySize(plt.attr[:size]...) - display(plt.o) -end - - -# function Base.display(::PlotsDisplay, subplt::Subplot{GadflyBackend}) -# setGadflyDisplaySize(getattr(subplt,1)[:size]...) -# ctx = buildGadflySubplotContext(subplt) -# -# # taken from Gadfly since I couldn't figure out how to do it directly -# -# filename = string(Gadfly.tempname(), ".html") -# output = open(filename, "w") -# -# plot_output = IOBuffer() -# Gadfly.draw(Gadfly.SVGJS(plot_output, Compose.default_graphic_width, -# Compose.default_graphic_height, false), ctx) -# plotsvg = takebuf_string(plot_output) -# -# write(output, -# """ -# -# -#
-#