### Button Interaction Setup Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/button.md This setup code defines a sequence of simulated user interactions for testing the button example. It includes mouse movements and clicks to automate the testing process. ```julia using ..FakeInteraction events = [ Wait(0.5), Lazy() do fig MouseTo(relative_pos(buttons[1], (0.3, 0.3))) end, LeftClick(), Wait(0.2), LeftClick(), Wait(0.2), LeftClick(), Wait(0.4), Lazy() do fig MouseTo(relative_pos(buttons[4], (0.7, 0.2))) end, Wait(0.2), LeftClick(), Wait(0.2), LeftClick(), Wait(0.2), LeftClick(), Wait(0.5) ] interaction_record(fig, "button_example.mp4", events) ``` -------------------------------- ### Install GLMakie Backend Source: https://github.com/makieorg/makie.jl/blob/master/README.md Install the GLMakie backend for interactive OpenGL visualizations. This is a common starting point for using Makie. ```julia julia>] ``` ```julia pkg> add GLMakie ``` -------------------------------- ### WSL Setup for GLMakie Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/glmakie.md Commands to set up a WSL environment for GLMakie, including installing necessary packages and configuring the display. This is a non-supported scenario. ```bash sudo apt install -y ubuntu-desktop mesa-utils export DISPLAY=localhost:0 glxgears ``` -------------------------------- ### WSL Ubuntu Desktop Setup for OpenGL Source: https://github.com/makieorg/makie.jl/blob/master/GLMakie/README.md Commands to set up an Ubuntu environment within WSL for OpenGL applications. This includes installing necessary packages and configuring the display environment. ```bash sudo apt install ubuntu-desktop mesa-utils export DISPLAY=localhost:0 glxgears ``` -------------------------------- ### Record Toggle Interaction Example Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/toggle.md Sets up a sequence of interactions to record a video of the toggle example. This includes waiting, simulating mouse movements, and clicks. ```julia using ..FakeInteraction events = [ Wait(0.5), Lazy() do fig MouseTo(relative_pos(toggle, (0.7, 0.3))) end, Wait(0.2), LeftClick(), Wait(2.0), LeftClick(), Wait(1.5), LeftClick(), Wait(2.0), ] interaction_record(fig, "toggle_example.mp4", events) ``` -------------------------------- ### Setup and Cleanup Interactions Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/axis.md Overload `registration_setup!` and `deregistration_cleanup!` to manage setup and cleanup logic for interactions that involve plot objects or other complex state. ```julia function Makie.registration_setup!(parent, interaction::MyInteraction) # Setup logic here end function Makie.deregistration_cleanup!(parent, interaction::MyInteraction) # Cleanup logic here end ``` -------------------------------- ### Voxel Texture Mapping Setup Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/plots/voxels.md Loads a texture image for use in voxel texture mapping. This example demonstrates loading the sprite sheet and displaying it using the `image` function. ```julia using FileIO texture = FileIO.load(Makie.assetpath("voxel_spritesheet.png")) image(0..1, 0..1, texture, axis=(xlabel = "u", ylabel="v")) ``` -------------------------------- ### Button Usage Example Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/button.md Demonstrates how to create and use a Button component, including handling click events and updating observable data. ```APIDOC ## Button ### Description A Button is a clickable UI element that can be used to trigger actions or events within the application. ### Usage ```julia using GLMakie GLMakie.activate!() # hide fig = Figure() ax = Axis(fig[1, 1]) fig[2, 1] = buttongrid = GridLayout(tellwidth = false) counts = Observable([1, 4, 3, 7, 2]) buttonlabels = [lift(x -> "Count: $(x[i])", counts) for i in 1:5] buttons = buttongrid[1, 1:5] = [Button(fig, label = l) for l in buttonlabels] for i in 1:5 on(buttons[i].clicks) do n counts[][i] += 1 notify(counts) end end barplot!(counts, color = cgrad(:Spectral)[LinRange(0, 1, 5)]) ylims!(ax, 0, 20) fig nothing # hide ``` ### Attributes ```@attrdocs Button ``` ``` -------------------------------- ### Install CairoMakie Package Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/tutorials/getting-started.md Installs the CairoMakie package and its dependencies. This command requires an internet connection and may take some time to complete. ```julia Pkg.add("CairoMakie") ``` -------------------------------- ### RPRMakie Initialization and Scene Setup Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/rprmakie.md Initializes the RPRMakie backend with specific settings and sets up a 3D scene with environment and point lights. Configure camera controls for optimal viewing. ```julia RPRMakie.activate!(iterations=200, plugin=RPR.Northstar) radiance = 50000 lights = [ EnvironmentLight(1.5, rotl90(load(assetpath("sunflowers_1k.hdr"))")), PointLight(Vec3f(50, 0, 200), RGBf(radiance, radiance, radiance*1.1)), ] s = Scene(size=(500, 500), lights=lights) cam3d!(s) c = cameracontrols(s) c.near[] = 5 c.far[] = 1000 update_cam!(s, c, Vec3f(100, 30, 80), Vec3f(0, 0, -10)) ``` -------------------------------- ### Basic Histogram Examples Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/plots/hist.md Demonstrates creating histograms with different binning strategies and visual customizations. Use this for basic data distribution visualization. ```julia data = randn(1000) f = Figure() hist(f[1, 1], data, bins = 10) hist(f[1, 2], data, bins = 20, color = :red, strokewidth = 1, strokecolor = :black) hist(f[2, 1], data, bins = [-5, -2, -1, 0, 1, 2, 5], color = :gray) hist(f[2, 2], data, normalization = :pdf) f ``` -------------------------------- ### DirectionalLight Examples Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/scene/lighting.md Illustrates the use of DirectionalLight, simulating a distant light source with parallel rays. The shading depends on the angle between the light and surface normals. Examples show lights with zero intensity, full intensity, and multiple lights with different colors and directions. ```julia fig = Figure(size = (600, 600)) ax11 = LScene(fig[1, 1], scenekw = (lights = [DirectionalLight(RGBf(0, 0, 0), Vec3f(-1, 0, 0))],)) ax12 = LScene(fig[1, 2], scenekw = (lights = [DirectionalLight(RGBf(1, 1, 1), Vec3f(-1, 0, 0))],)) lights = [ DirectionalLight(RGBf(0, 0, 0.7), Vec3f(-1, -1, 0)), DirectionalLight(RGBf(0.7, 0.2, 0), Vec3f(-1, 1, -1)), DirectionalLight(RGBf(0.7, 0.7, 0.7), Vec3f(1, -1, -1)) ] ax21 = LScene(fig[2, 1], scenekw = (lights = lights,)) ax22 = LScene(fig[2, 2]) set_ambient_light!(ax22, RGBf(0,0,0)) set_lights!(ax22, [DirectionalLight(RGBf(4, 2, 1), Vec3f(0, 0, -1))]) for ax in (ax11, ax12, ax21, ax22) mesh!(ax, Sphere(Point3f(0), 1f0), color = :white) end fig ``` -------------------------------- ### Example Listener Callback Source: https://github.com/makieorg/makie.jl/wiki/ArgumentsObservable Defines an example listener function that prints information about changed arguments, including the set of updated identifiers and the new values for 'x' and 'color' if they were changed. ```julia on(ao, 1, :color) do changed, x, color println("What changed?") println(changed) if 1 in changed println("New x length: $(length(x))") end if :color in changed println("New color length: $(length(color))") end end ``` -------------------------------- ### Record Menu Interaction Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/menu.md Sets up a sequence of simulated user interactions with the menus to record an example video. This is used for generating the accompanying video demonstration. ```julia using ..FakeInteraction events = [ Wait(1), Lazy() do fig MouseTo(relative_pos(menu, (0.3, 0.3))) end, LeftClick(), Wait(0.5), Lazy() do fig MouseTo(relative_pos(menu, (0.33, -0.6))) end, Wait(0.2), LeftClick(), Wait(0.5), Lazy() do fig MouseTo(relative_pos(menu2, (0.28, 0.3))) end, Wait(0.2), LeftClick(), Wait(0.2), Lazy() do fig MouseTo(relative_pos(menu2, (0.4, -3.6))) end, Wait(0.2), LeftClick(), Wait(2), ] interaction_record(fig, "menu_example.mp4", events) ``` -------------------------------- ### Activate GLMakie Backend Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/glmakie.md Call `GLMakie.activate!()` to activate the native desktop backend. This is typically done once at the start of your application. ```julia GLMakie.activate!() ``` -------------------------------- ### Develop Makie Backends Locally Source: https://github.com/makieorg/makie.jl/blob/master/README.md Installs Makie and its backends in development mode for local modifications. Requires Julia's package manager. ```julia ]dev --local Makie GLMakie CairoMakie WGLMakie RPRMakie ``` -------------------------------- ### WSL Troubleshooting: Install Dependencies Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/glmakie.md Install additional development libraries required for graphics and X11 on WSL. This is part of the troubleshooting steps for display issues. ```bash sudo apt install -y xorg-dev mesa-utils xvfb libgl1 freeglut3-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libxext-dev ``` -------------------------------- ### Bonito Interactive Color Picker Example Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/wglmakie.md An example of a Bonito application featuring a hue slider that dynamically updates the background color of a styled `div` element. ```julia using Colors using Bonito App() do session::Session hue_slider = Slider(0:360) color_swatch = DOM.div(class="h-6 w-6 p-2 m-2 rounded shadow") onjs(session, hue_slider.value, js"""function (hue){ $(color_swatch).style.backgroundColor = "hsl(" + hue + ",60%,50%)" }""" ) return Row(hue_slider, color_swatch) end ``` -------------------------------- ### Initialize ArgumentsObservable Source: https://github.com/makieorg/makie.jl/wiki/ArgumentsObservable Example initialization of an ArgumentsObservable with sample positional and keyword arguments. ```julia ao = ArgumentsObservable(Arguments(randn(100), randn(100), color = randn(100)), []) ``` -------------------------------- ### Makie Package Extension Setup Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/recipes.md This demonstrates the basic structure for a Makie package extension. It involves defining exported functions in the main package and then adding methods to these functions in the extension package. ```julia module SomePackage export someplot export someplot! # functions with no methods function someplot end function someplot! end end # module ``` ```julia module MakieExtension using SomePackage import SomePackage: someplot, someplot! Makie.convert_single_argument(v::SomeVector) = v.v @recipe(SomePlot) do scene Theme() end function Makie.plot!(p::SomePlot) lines!(p, p[1]) scatter!(p, p[1]) return p end end # module ``` -------------------------------- ### Activate WGLMakie Backend Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/backends.md Use this snippet to activate the WGLMakie backend for browser-based plotting. Ensure WGLMakie is installed. ```julia using WGLMakie WGLMakie.activate!() ``` -------------------------------- ### Texture, Pattern, and Matcap Examples in Makie Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/colors.md Demonstrates how to apply image textures, hatching patterns, and matcap materials to 3D objects using Makie.jl. Requires GLMakie and FileIO. ```julia using GLMakie, FileIO f = Figure() mesh(f[1, 1], Rect2f(0,0,1,1), color = load(Makie.assetpath("cow.png")), shading = NoShading, axis=(title ="texture",)) mesh(f[2, 1], Rect2f(0,0,1,1), color = Pattern('/'), shading = NoShading, axis=(title ="Pattern",)) hidedecorations!.(f.content) catmesh = FileIO.load(assetpath("cat.obj")) texture = FileIO.load(assetpath("diffusemap.png")) matcap = FileIO.load(Base.download("https://raw.githubusercontent.com/nidorx/matcaps/master/1024/E6BF3C_5A4719_977726_FCFC82.png")) Label(f[1, 2][1, 1], "texture 3D", tellwidth = false) a, p = mesh(f[1, 2][2, 1], catmesh, color = texture, axis = (show_axis = false, )) Label(f[2, 2][1, 1], "matcap", tellwidth = false) mesh(f[2, 2][2, 1], catmesh, matcap = matcap, shading = NoShading, axis = (show_axis = false, )) f ``` -------------------------------- ### Legend Interaction Setup Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/legend.md Sets up a sequence of events to simulate user interactions with the legend for recording an animation. This includes mouse movements, clicks, and waits to control the timing of the interaction sequence. ```julia using ..FakeInteraction _events = [ Wait(0.5), Lazy() do fig MouseTo(relative_pos(leg, (0.6, 0.8))) end, Wait(0.2), LeftClick(), Wait(1.5), Lazy() do fig MouseTo(relative_pos(leg, (0.6, 0.5))) end, Wait(0.2), LeftClick(), Wait(1.5), RightClick(), Wait(1.5), Lazy() do fig MouseTo(relative_pos(leg, (0.6, 0.7))) end, Wait(0.2), LeftClick(), Wait(1.5), MiddleClick(), Wait(1.5) ] interaction_record(fig, "legend_interaction_example.mp4", _events) ``` -------------------------------- ### Start Using Makie Package Source: https://github.com/makieorg/makie.jl/blob/master/README.md Import the GLMakie package into your Julia session to begin creating visualizations. This is the standard way to load the library. ```julia using GLMakie ``` -------------------------------- ### IntervalSlider Interaction Setup Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/intervalslider.md Sets up a sequence of simulated user interactions for testing and recording the behavior of the IntervalSlider component. This includes mouse movements, clicks, and drags to demonstrate interval manipulation. ```julia using ..FakeInteraction events = [ Wait(1), Lazy() do fig MouseTo(relative_pos(rs_h, (0.2, 0.5))) end, Wait(0.2), LeftDown(), Wait(0.3), Lazy() do fig MouseTo(relative_pos(rs_h, (0.5, 0.6))) end, Wait(0.2), LeftUp(), Wait(0.5), Lazy() do fig MouseTo(relative_pos(rs_h, (0.625, 0.4))) end, Wait(0.2), LeftDown(), Wait(0.3), Lazy() do fig MouseTo(relative_pos(rs_h, (0.375, 0.5))) end, Wait(0.5), Lazy() do fig MouseTo(relative_pos(rs_h, (0.8, 0.5))) end, LeftUp(), Wait(0.5), Lazy() do fig MouseTo(relative_pos(rs_v, (0.5, 0.66))) end, Wait(0.3), LeftDown(), Lazy() do fig MouseTo(relative_pos(rs_v, (0.5, 0.33))) end, LeftUp(), Wait(0.5), Lazy() do fig MouseTo(relative_pos(rs_v, (0.5, 0.8))) end, Wait(0.3), LeftClick(), Wait(2), ] interaction_record(f, "intervalslider_example.mp4", events) ``` -------------------------------- ### Interactive 3D Plotting with WGLMakie Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/wglmakie.md Demonstrates creating an interactive 3D surface plot using WGLMakie. This example showcases the interactivity that is maintained even for complex 3D visualizations. ```julia N = 60 function xy_data(x, y) r = sqrt(x^2 + y^2) r == 0.0 ? 1f0 : (sin(r)/r) end l = range(-10, stop = 10, length = N) z = Float32[xy_data(x, y) for x in l, y in l] surface( -1..1, -1..1, z, colormap = :Spectral ) ``` -------------------------------- ### Setup Axes and Plot Data in Panel A Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/tutorials/layout-tutorial.md Create and link multiple axes within a GridLayout, then plot scatter and density data. Ensure axes are linked for synchronized zooming and panning. ```julia axtop = Axis(ga[1, 1]) axmain = Axis(ga[2, 1], xlabel = "before", ylabel = "after") axright = Axis(ga[2, 2]) linkyaxes!(axmain, axright) linkxaxes!(axmain, axtop) labels = ["treatment", "placebo", "control"] data = randn(3, 100, 2) .+ [1, 3, 5] for (label, col) in zip(labels, eachslice(data, dims = 1)) scatter!(axmain, col, label = label) density!(axtop, col[:, 1]) density!(axright, col[:, 2], direction = :y) end f ``` -------------------------------- ### Align Neighboring Axis Labels (Initial Setup) Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/axis.md Demonstrates a scenario where axis labels are misaligned due to varying tick label lengths. This sets up the axes before alignment adjustments. ```julia f = Figure() ax1 = Axis(f[1, 1], title = "Axis 1", ylabel = "y label", ytickformat = "{:.3f}") ax2 = Axis(f[2, 1], title = "Axis 2", ylabel = "y label", xlabel = "x label") ax3 = Axis(f[2, 2], title = "Axis 3", xlabel = "x label", xtickformat = "{:.3f}", xticklabelrotation = pi/4) f ``` -------------------------------- ### Apply a Custom Fontsize Theme Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/theming/themes.md This example shows how to define a custom theme to change the default fontsize and apply it using `set_theme!`. Subsequent plots will use this new theme. ```julia fontsize_theme = Theme(fontsize = 10) set_theme!(fontsize_theme) example_plot() ``` -------------------------------- ### Prepare and Configure Lights for a Scene Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/scene/lighting.md Sets up a list of lights including AmbientLight and RectLights, then modifies RectLights by rotating and translating them. Requires Makie and GeometryBasics. ```julia fig = Figure(backgroundcolor = :black) # Prepare lights lights = Makie.AbstractLight[ AmbientLight(RGBf(0.1, 0.1, 0.1)), RectLight(RGBf(0.9, 1, 0.8), Rect2f(-1.9, -1.9, 1.8, 1.8)), RectLight(RGBf(0.9, 1, 0.8), Rect2f(-1.9, 0.1, 1.8, 1.8)), RectLight(RGBf(0.9, 1, 0.8), Rect2f( 0.1, 0.1, 1.8, 1.8)), RectLight(RGBf(0.9, 1, 0.8), Rect2f( 0.1, -1.9, 1.8, 1.8)), ] lights = map(lights) do l if l isa RectLight angle = pi/4 p = l.position l = Makie.rotate(l, Vec3f(0, 1, 0), angle) p = 3 * Vec3f(1+sin(angle), 0, cos(angle)) + p[1] * normalize(l.u1) + p[2] * normalize(l.u2) l = Makie.translate(l, p) end return l end ``` -------------------------------- ### Initialize and Configure ComputeGraph Source: https://github.com/makieorg/makie.jl/blob/master/ComputePipeline/README.md Demonstrates how to initialize a ComputeGraph, add inputs with and without direct type conversion, and register computations. ```julia graph = ComputeGraph() # add inputs add_input!(graph, :input1, 1) add_input!((key, value) -> Float32(value), graph, :input2, 2) # directly converts # add computations (edges + output nodes) register_computation!(graph, [:input1, :input2], [:output]) do inputs, changed, last_output input1, input2 = inputs return (input1 + input2, ) end ``` -------------------------------- ### Set Up Scene with Lights and Background Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/scene/lighting.md Initializes an LScene with specified lights, background color, and camera settings. Ensures the scene is not centered. ```julia # Set scene scene = LScene( fig[1, 1], show_axis = false, scenekw=(lights = lights, backgroundcolor = :black, center = false), ) ``` -------------------------------- ### Complete Inset Plot Code Example Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/tutorials/inset-plot-tutorial.md A comprehensive code snippet combining all steps to create a figure with an inset plot, including data generation, axis setup, plotting, legend, and marking the zoomed area. ```julia # Load the packages using CairoMakie using Random # Generate dummy stock price data Random.seed!(123) time = 1:500 stock_price = cumsum(randn(500) .+ 0.5) # Create a figure fig = Figure(size=(800, 600)) # Main plot ax_main = Axis(fig[1, 1], title="Stock Price Over Time", xlabel="Days", ylabel="Price") line_main = lines!(ax_main, time, stock_price, color=:blue) # Inset axis ax_inset = Axis(fig[1, 1], width=Relative(0.2), height=Relative(0.2), halign=0.1, valign=0.9, title="Zoomed View") # Set xlims for a selected time data range xlims!(ax_inset, 50, 70) # Calculate and set ylims dynamically for the selected time data range min_price, max_price = extrema(stock_price[50:70]) ylims!(ax_inset, min_price, max_price) # Plot the data in the inset axis line_inset = lines!(ax_inset, time, stock_price, color=:red) # Z-Ordering for rendering order translate!(ax_inset.blockscene, 0, 0, 150) # Legend Legend(fig[1, 2], [line_main, line_inset], ["Stock Price", "Zoomed Region"]) # Mark the zoomed section (x, y, width, height) border_rect = Rect2(50, min_price, 20, max_price - min_price) lines!(ax_main, border_rect, color=:black, linewidth=1) fig ``` -------------------------------- ### Preload libstdc++ for OpenGL Errors Source: https://github.com/makieorg/makie.jl/blob/master/GLMakie/README.md If you encounter libc library mismatches causing OpenGL errors, try preloading the correct libstdc++.so.6 library when starting Julia. This is a common fix for remote SSH or WSL setups. ```sh LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 julia ``` -------------------------------- ### SpotLight Configuration Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/scene/lighting.md Shows how to set up SpotLights, which illuminate within a cone. The cone is defined by a direction and angles for intensity falloff. This example displays three SpotLights with different colors, positions, and cone properties. ```julia GLMakie.closeall() # hide lights = [ SpotLight(RGBf(1, 0, 0), Point3f(-3, 0, 3), Vec3f(0, 0, -1), Vec2f(0.0, 0.3pi)), SpotLight(RGBf(0, 1, 0), Point3f( 0, 3, 3), Vec3f(0, -0.5, -1), Vec2f(0.2pi, 0.25pi)), SpotLight(RGBf(0, 0, 1), Point3f( 3, 0, 3), Vec3f(0, 0, -1), Vec2f(0.25pi, 0.25pi)), ] fig = Figure(size = (600, 600)) ax = LScene(fig[1, 1], scenekw = (lights = lights,)) ps = [Point3f(x, y, 0) for x in -5:5 for y in -5:5] meshscatter!(ax, ps, color = :white, markersize = 0.75) scatter!(ax, map(l -> l.position, lights), color = map(l -> l.color, lights), strokewidth = 1, strokecolor = :black) fig ``` -------------------------------- ### Initialize Blocks Overview Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/overview.md This code snippet is used internally to set up the overview section for blocks in the documentation. It imports necessary modules and calls a helper function. ```julia using Markdown # hide import ..MakieDocsHelpers # hide MakieDocsHelpers.OverviewSection("blocks") # hide ``` -------------------------------- ### Check Installed Package Version Source: https://github.com/makieorg/makie.jl/blob/master/README.md Command to check the installed version of a package, such as GLMakie. Useful for debugging or verifying installation. ```julia ]st GLMakie ``` -------------------------------- ### Toggle Usage Example Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/toggle.md This example demonstrates how to create and use a Toggle in a Makie.jl plot. The toggle's state is used to control the live update of a plot. ```APIDOC ## Toggle A toggle with an attribute `active` that can either be true or false, to enable or disable properties of an interactive plot. ### Attributes #### `active` (Observable{Bool}) Determines whether the toggle is currently active (true) or inactive (false). ### Example Usage ```julia using GLMakie GLMakie.activate!() # hide fig = Figure() ax = Axis(fig[1, 1], limits = (0, 600, -2, 2)) hidexdecorations!(ax) t = Observable(0.0) points = lift(t) do t x = range(t-1, t+1, length = 500) @. sin(x) * sin(2x) * sin(4x) * sin(23x) end lines!(ax, points, color = (1:500) .^ 2, linewidth = 2, colormap = [(:blue, 0.0), :blue]) gl = GridLayout(fig[2, 1], tellwidth = false) Label(gl[1, 1], "Live Update") toggle = Toggle(gl[1, 2], active = false) on(fig.scene.events.tick) do tick toggle.active[] || return t[] += tick.delta_time end fig nothing # hide ``` ``` -------------------------------- ### Using Predefined Materials with RPRMakie Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/rprmakie.md Demonstrates setting up the RPRMakie screen with the Northstar backend and applying various predefined materials to a scene. Includes environment and point lights, and saving the rendered image. ```julia using GeometryBasics, RPRMakie using Colors, FileIO using Colors: N0f8 radiance = 500 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] fig = Figure(; size=(1500, 700)); ax = LScene(fig[1, 1]; show_axis=false, scenekw=(; lights=lights)) screen = RPRMakie.Screen(ax.scene; plugin=RPR.Northstar, iterations=400) matsys = screen.matsys emissive = RPR.EmissiveMaterial(matsys) diffuse = RPR.DiffuseMaterial(matsys) glass = RPR.Glass(matsys) plastic = RPR.Plastic(matsys) chrome = RPR.Chrome(matsys) dielectric = RPR.DielectricBrdfX(matsys) gold = RPR.SurfaceGoldX(matsys) materials = [glass chrome; gold dielectric; emissive plastic] mesh!(ax, GeometryBasics.Mesh(load(Makie.assetpath("matball_floor.obj"))); color=:white) palette = reshape(Makie.wong_colors()[1:6], size(materials)) for i in CartesianIndices(materials) x, y = Tuple(i) mat = materials[i] mplot = if mat === emissive matball!(ax, diffuse; inner=emissive, color=nothing) else matball!(ax, mat; color=nothing) end v = Vec3f(((x, y) .- (0.5 .* size(materials)) .- 0.5)..., 0) translate!(mplot, 0.9 .* (v .- Vec3f(0, 3, 0))) end cam = cameracontrols(ax.scene) cam.eyeposition[] = Vec3f(-0.3, -5.5, 0.9) cam.lookat[] = Vec3f(0.5, 0, -0.5) cam.upvector[] = Vec3f(0, 0, 1) cam.fov[] = 35 emissive.color = Vec3f(4, 2, 2) image = colorbuffer(screen) save("materials.png", image) ``` -------------------------------- ### Get All Objects At A Position With contents Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/figure.md Use the `contents` function to get a Vector of all objects at a given `GridPosition`. The `exact = true` keyword argument ensures that only objects directly at that position are returned, not those in nested layouts. ```julia f = Figure() box = f[1:3, 1:2] = Box(f) ax = f[1, 1] = Axis(f) contents(f[1, 1]) == [ax] contents(f[1:3, 1:2]) == [box, ax] contents(f[1:3, 1:2], exact = true) == [box] ``` -------------------------------- ### Cart and Arms Transformation Example Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/generic/transformations.md Demonstrates constructing and applying transformations to create a dynamic scene with a cart, arms, and a rope. This example utilizes sliders to control the cart's translation, arm rotations, and rope length, showcasing how transformations can be chained and modified. ```julia using Makie: Vec3d f = Figure(size = (600, 400)) a = Axis(f[2, 2], aspect = DataAspect()) ylims!(0, 3); xlims!(-3, 3) # Cart cart = Transformation() scatter!(a, [-0.32, -0.15, 0.15, 0.32], fill(0.09, 4), transformation = cart, marker = Circle, color = :transparent, strokewidth = 2, strokecolor = :black, markerspace = :data, markersize = 0.1 ) linesegments!(a, [-0.4, 0.4], [0.2, 0.2], transformation = cart, color = :black, linewidth = 5 ) # arms arm1 = Transformation(cart, origin = Vec3d(0, 0.2, 0)) linesegments!(a, [0, 0], [0.2, 2], transformation = arm1, color = :black, linewidth = 5, linecap = :round ) arm2 = Transformation(arm1, origin = Vec3d(0, 2, 0)) linesegments!(a, [0.0, 1.5], [2, 2], transformation = arm2, color = :black, linewidth = 5, linecap = :round ) # rope - we want this to just extend downwards rather than inherit rotations rope_length = Observable(1.0) rope_points = map(arm2.model, rope_length) do model, len # position of end of arm2 after transformations apply rope_origin = (model * Point4(1.5, 2, 0, 1))[Vec(1,2)] rope_end = rope_origin - Vec2(0, len) return [rope_origin, rope_end] end crate_origin = map(ps -> ps[2] .+ Vec2(0, -0.12), rope_points) linesegments!(a, rope_points, color = :black, linewidth = 3, linestyle = :dot, linecap = :round ) scatter!(a, crate_origin, marker = Rect, color = :white, strokewidth = 2, strokecolor = :black, markerspace = :data, markersize = Vec2f(0.3, 0.2) ) # Move cart sl1 = Slider(f[3, 2], range = range(-4, 4, length = 101)) on(v -> translate!(cart, v, 0, 0), sl1.value) # Pivot arm 1 sl2 = Slider(f[1, 2], range = range(-pi/3, pi/3, length = 101)) on(v -> Makie.rotate!(arm1, -v), sl2.value) # Pivot arm 2 sl3 = Slider(f[2, 1], range = range(-pi/3, pi/3, length = 101), horizontal = false) on(v -> Makie.rotate!(arm2, -v), sl3.value) # Extend rope sl4 = Slider(f[2, 3], range = range(2, 0.1, length = 101), startvalue = 1.0, horizontal = false) on(v -> rope_length[] = v, sl4.value) # Set up some configuration set_close_to!(sl1, -1.0) # move cart to -1 set_close_to!(sl2, -0.5) # angle arm1 to the left set_close_to!(sl3, 0.5) # counter-angle arm2 to be horizontal set_close_to!(sl4, 0.5) # raise crate f ``` -------------------------------- ### Visualize Camera View Box with Makie.jl Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/cameras.md This example demonstrates how to visualize the camera's view box by rendering the frustum in a separate scene. It requires GeometryBasics and LinearAlgebra. The code sets up two scenes: one for the primary visualization and another to display the camera's frustum. ```julia using GeometryBasics, LinearAlgebra function frustum_snapshot(cam) r = Rect3f(-1, -1, -1, 2, 2, 2) rect_ps = Makie.convert_arguments(Lines, r)[1] inv_pv = inv(cam.projectionview[]) return map(rect_ps) do p p = inv_pv * to_ndim(Point4f, p, 1) return p[Vec(1,2,3)] / p[4] end end ex = Point3f(1,0,0) ey = Point3f(0,1,0) ez = Point3f(0,0,1) fig = Figure() # Set up Scene shown by a camera scene = LScene(fig[1, 1]) cc = Makie.Camera3D(scene.scene, projectiontype = Makie.Perspective, center = false) linesegments!(scene, Rect3f(Point3f(-1), Vec3f(2)), color = :black) linesegments!(scene, [-ex, ex, -ey, ey, -ez, ez], color = [:red, :red, :green, :green, :blue, :blue] ) center!(scene.scene) cam = scene.scene.camera eyeposition = cc.eyeposition lookat = cc.lookat frustum = map(pv -> frustum_snapshot(cam), cam.projectionview) # Set up scene visualizing the cameras view scene = LScene(fig[1, 2]) _cc = Makie.Camera3D(scene.scene, projectiontype = Makie.Orthographic, center = false) lines!(scene, frustum, color = :blue, linestyle = :dot) scatter!(scene, eyeposition, color = :black) scatter!(scene, lookat, color = :black) linesegments!(scene, [-ex, ex, -ey, ey, -ez, ez], color = [:red, :red, :green, :green, :blue, :blue] ) linesegments!(scene, Rect3f(Point3f(-1), Vec3f(2)), color = :black) # Tweak initial camera position update_cam!(scene.scene, Vec3f(4.5, 2.5, 3.5), Vec3f(0)) update_cam!(scene.scene, Vec3f(6, 8, 5), Vec3f(0)) fig ``` -------------------------------- ### Basic Boxplot Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/plots/boxplot.md A simple example demonstrating how to create a basic boxplot with categories and values. ```APIDOC ## Basic Boxplot ### Description Creates a boxplot with specified categories and values. ### Usage ```julia categories = rand(1:3, 1000) values = randn(1000) boxplot(categories, values) ``` ``` -------------------------------- ### Plot Stock Data with Custom Recipe Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/recipes.md Demonstrates how to use the `StockChart` recipe by generating sample stock data and plotting it. This shows the practical application of the defined recipe. ```julia timestamps = 1:100 startvalue = StockValue(0.0, 0.0, 0.0, 0.0) stockvalues = foldl(timestamps[2:end], init = [startvalue]) do values, t open = last(values).close + 0.3 * randn() close = open + randn() high = max(open, close) + rand() low = min(open, close) - rand() push!(values, StockValue( open, close, high, low )) end f = Figure() stockchart(f[1, 1], timestamps, stockvalues) ``` -------------------------------- ### Create RPR Context Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/rprmakie.md Initializes a RadeonProRender context. This is a basic setup step for using the RPR backend. ```julia using RadeonProRender RPRMakie.Context() ``` -------------------------------- ### Create and Interact with Menus Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/blocks/menu.md Demonstrates creating two menus: one for colormaps and another for mathematical functions. It shows how to link menu selections to plot updates and axis limits. ```julia using GLMakie GLMakie.activate!() # hide fig = Figure() menu = Menu(fig, options = ["viridis", "heat", "blues"], default = "blues") funcs = [sqrt, x->x^2, sin, cos] menu2 = Menu(fig, options = zip(["Square Root", "Square", "Sine", "Cosine"], funcs), default = "Square") fig[1, 1] = vgrid!( Label(fig, "Colormap", width = nothing), menu, Label(fig, "Function", width = nothing), menu2; tellheight = false, width = 200) ax = Axis(fig[1, 2]) func = Observable{Any}(funcs[1]) ys = lift(func) do f f.(0:0.3:10) end scat = scatter!(ax, ys, markersize = 10px, color = ys) cb = Colorbar(fig[1, 3], scat) on(menu.selection) do s scat.colormap = s end notify(menu.selection) on(menu2.selection) do s func[] = s autolimits!(ax) end notify(menu2.selection) fig nothing # hide ``` -------------------------------- ### Load CairoMakie Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/tutorials/getting-started.md Loads the CairoMakie package into your Julia session, making its plotting functions available. This should be done after installation. ```julia using CairoMakie ``` -------------------------------- ### Activate Pkg Environment Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/tutorials/getting-started.md Activates the current directory as a Pkg environment. This ensures that packages are installed locally for your project. ```julia using Pkg Pkg.activate(".") ``` -------------------------------- ### Basic Step Histograms Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/plots/stephist.md Demonstrates creating step histograms with different bin counts and styling. Use this to visualize data distributions with varying granularity and appearance. ```julia data = randn(1000) f = Figure() stephist(f[1, 1], data, bins = 10) stephist(f[1, 2], data, bins = 20, color = :red, linewidth = 3) stephist(f[2, 1], data, bins = [-5, -2, -1, 0, 1, 2, 5], color = :gray) stephist(f[2, 2], data, normalization = :pdf) f ``` -------------------------------- ### Basic Tooltip Example Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/plots/tooltip.md Demonstrates how to add a simple tooltip to a scatter plot. The tooltip is associated with a specific point. ```julia fig, ax, p = scatter(Point2f(0), marker = 'x', markersize = 20) tooltip!(Point2f(0), "This is a tooltip pointing at x") fig ``` -------------------------------- ### Initialize Plots Overview Section Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/plots/overview.md This code snippet is used internally to set up the overview section for plots. It requires importing Markdown and a helper module. ```julia using Markdown # hide import ..MakieDocsHelpers # hide MakieDocsHelpers.OverviewSection("plots") # hide ``` -------------------------------- ### Basic Keyboard Event Handling Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/events.md Observe keyboard events and check for a specific key. This is a basic setup before using `ispressed`. ```julia hotkey = Keyboard.a on(events(fig).keyboardbutton) do event if event.key == hotkey ... end end ``` -------------------------------- ### Setup Scene with Lights and Materials Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/explanations/backends/rprmakie.md Configures a Makie scene with RPR-specific lights and materials. Note that RPRMakie currently only supports LScene and requires manual context management for custom materials to avoid segfaults. ```julia fig = Figure() radiance = 10000 lights = [ EnvironmentLight(0.5, Makie.FileIO.load(RPR.assetpath("studio026.exr"))), PointLight(Vec3f(0, 0, 20), RGBf(radiance, radiance, radiance)) ] ax = LScene(fig[1, 1]; show_axis = false, scenekw=(lights=lights,)) screen = RPRMakie.Screen(ax.scene; iterations=10, plugin=RPR.Northstar) matsys = screen.matsys context = screen.context mat = RPR.Chrome(matsys) mesh!(ax, Sphere(Point3f(0), 1), material=mat) ``` -------------------------------- ### 2D Arrows Example Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/reference/plots/arrows.md Generates a 2D plot with arrows based on calculated `us` and `vs` components. The arrow color is determined by their strength. ```julia f = Figure(size = (800, 800)) Axis(f[1, 1], backgroundcolor = "black") xs = LinRange(0, 2pi, 20) ys = LinRange(0, 3pi, 20) us = [sin(x) * cos(y) for x in xs, y in ys] vs = [-cos(x) * sin(y) for x in xs, y in ys] strength = vec(sqrt.(us .^ 2 .+ vs .^ 2)) arrows2d!(xs, ys, us, vs, lengthscale = 0.2, color = strength) f ``` -------------------------------- ### Initialize Figure with Custom Background and Size Source: https://github.com/makieorg/makie.jl/blob/master/docs/src/tutorials/layout-tutorial.md Sets up the main figure with a specific background color and dimensions. CairoMakie is activated for rendering. ```julia using CairoMakie using Makie.FileIO CairoMakie.activate!() # hide f = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98), size = (1000, 700)) ```