### Setup Makie Plotting Environment in Julia Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/MarketData Imports necessary libraries for data manipulation and plotting with Makie. Ensures the environment is ready for creating visualizations. ```julia using MarketData, DataFrames using AlgebraOfGraphics, CairoMakie using Statistics ``` -------------------------------- ### Setup Julia Makie Visualization Environment Source: https://beautiful.makie.org/dev/examples/datavis/multipleTitles Initializes the CairoMakie backend and sets up the random number generator for reproducible data generation. This snippet demonstrates the basic requirements for creating Makie visualizations in Julia, including package imports and seed setting for consistent results. ```julia using CairoMakie using Random ``` ```julia Random.seed!(1234) ``` -------------------------------- ### Setup Scene with Lights and Sphere/Plane Mesh (Julia) Source: https://beautiful.makie.org/dev/examples/rpr/sphere_plane This code sets up a Makie scene using RPRMakie for rendering. It defines background sky color using an image, adds environment and point lights, creates a custom tessellated sphere mesh, and a plane mesh. The meshes are then added to the scene with specific materials and rendered using RPRMakie. ```julia using GLMakie, GeometryBasics using RPRMakie, RadeonProRender using LinearAlgebra, Colors, FileIO # Background/sky color img = [colorant"grey90" for i in 1:1, j in 1:1] # Lights setup lights = [EnvironmentLight(1.0, img'), PointLight(Vec3f(2,0,2.0), RGBf(8.0, 6.0, 5.0))] # Custom Tesselation over a Sphere function SphereTess(; o=Point3f(0), r=1, tess=64) return uv_normal_mesh(Tesselation(Sphere(o, r), tess)) end plane = Rect3f(Vec3f(-5,-2,-1.05), Vec3f(10,4,0.05)) # Scene setup fig=Figure(; size=(900, 900)) ax=LScene(fig[1, 1]; show_axis=false, scenekw=(;lights=lights)) screen=RPRMakie.RPRScreen(size(ax.scene); plugin=RPR.Northstar, iterations=250) matsys=screen.matsys mesh!(ax, SphereTess(); color=RGB(0.082, 0.643, 0.918), material=RPR.DiffuseMaterial(matsys)) mesh!(ax, plane; color=:gainsboro, material=RPR.DiffuseMaterial(matsys)) GLMakie.activate!() zoom!(ax.scene, cameracontrols(ax.scene), 0.22) display(fig) context, task = RPRMakie.replace_scene_rpr!(ax.scene, screen) # Avoid printing stuff into the repl println(nothing) imageOut = colorbuffer(screen) # save("SpherePlaneSky.png", imageOut) # save just screen scene. ``` -------------------------------- ### Activate CairoMakie PNG Source: https://beautiful.makie.org/dev/examples/datavis/fractals This snippet activates the CairoMakie backend for generating PNG images. It establishes the foundation for creating visualizations using Makie.jl. No dependencies beyond the core Makie library are required. ```julia using CairoMakie using StatsBase using LinearAlgebra using Interpolations CairoMakie.activate!(type = "png") ``` -------------------------------- ### Initialize Makie and Algebra of Graphics Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/scatterlinesAoG This snippet initializes the necessary libraries for plotting with Makie and Algebra of Graphics in Julia. It imports both `CairoMakie` for rendering and `AlgebraOfGraphics` for declarative plotting. ```julia using CairoMakie, AlgebraOfGraphics ``` -------------------------------- ### Apply Dark Theme and Display Stats with Makie Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/datasaurus Renders a Makie plot using a dark theme, similar to the previous example but with a darker background. It also displays calculated statistics (mean, std, correlation) for the dataset on the plot. ```julia with_theme(theme_dark(), size = (1600,1200), fontsize = 24) do fig = Figure() g = GridLayout(fig[1,1]) wfacet = draw!(g, plt) ## palettes = (layout=wrap(cols=3),) # this should be also something automatic from AoG bxs = [Box(g[i,j, Top()], color = (:grey30, 0.25), strokevisible = false) for i in 1:4 for j in 1:4] [translate!(bxs[i].blockscene, 0,0,-1) for i in 1:15] delete!.(bxs[14:end]) # plot some stats axstats = Axis(g[4, 2]) [text!(axstats, t, position = (0.05, 0.9 - (i-1)*0.15), align = (:left, :top)) for (i,t) in enumerate(names(stats)[2:end])] [text!(axstats, ": "*string(t), position = (0.3, 0.9 - (i-1)*0.15), align = (:left, :top)) for (i,t) in enumerate(values(stats[1,2:end]))] limits!(0,1,0,1) hidedecorations!(axstats) fig end ``` -------------------------------- ### Create Heatmaps with Colorbars in Julia using Makie Source: https://beautiful.makie.org/dev/examples/2d/heatmaps/heatmapGrid Generates a figure with multiple heatmap plots using the Makie.jl library. This example utilizes random data and various colormaps to illustrate heatmap customization. Dependencies include CairoMakie, Random, and ColorSchemes. ```julia using CairoMakie, Random, ColorSchemes Random.seed!(21) cmaps = collect(keys(colorschemes)) fig = Figure(; size = (1200, 800), fontsize = 20) for i in 1:2, j in 1:2:5 ax = Axis(fig[i, j], aspect = 1, xticks = [1, 10], yticks = [1, 10]) hmap = heatmap!(ax, 1:10, 1:10, rand(10, 10); colorrange = (0, 1), colormap = cmaps[rand(1:length(cmaps))]) Colorbar(fig[i, j+1], hmap; height = Relative(0.5), tickwidth = 2, ticks = [0, 0.5, 1]) end fig ``` -------------------------------- ### Create 3D Vertical Band on Map with GeoMakie (Julia) Source: https://beautiful.makie.org/dev/examples/geo/vertical_feature_mask This example demonstrates how to create a 3D vertical band over a world map using GeoMakie and GLMakie in Julia. It involves loading an earth image, drawing coastlines, and then creating a band with varying colors based on its position. Dependencies include GLMakie, GeoMakie, Downloads, and FileIO. The output is an interactive 3D visualization. ```julia using GLMakie, GeoMakie using Downloads: download using FileIO GLMakie.activate!() earth_img = load(download("https://upload.wikimedia.org/wikipedia/commons/5/56/Blue_Marble_Next_Generation_%2B_topography_%2B_bathymetry.jpg")) fig = Figure(; size=(800, 400), fontsize=22) ax = LScene(fig[1,1]) lines!(ax, GeoMakie.coastlines(), transparency=true) lines!(ax, GeoMakie.coastlines()[95], color=:red, linewidth=5, transparency=true) image!(ax, -180..180, -90..90, earth_img'[:,end:-1:1]) fig idx_l = findmax(length.(GeoMakie.coastlines())) longpath = GeoMakie.coastlines()[idx_l[2]] @show idx_l linepath = Point3f[] for p in longpath.points push!(linepath, Point3f(p..., 0)) push!(linepath, Point3f(p..., 0)) end linepathh = Point3f[] for p in longpath.points push!(linepathh, Point3f(p..., 20)) push!(linepathh, Point3f(p..., 20)) end fig = Figure(size=(800, 400), fontsize=22) ax = LScene(fig[1,1]; show_axis=false) lines!(ax, GeoMakie.coastlines(), transparency=true, color=:white) lines!(ax, linepath, color = :orangered, linewidth=2.5, transparency=true) lines!(ax, linepathh, color = :white, linewidth=2.5, transparency=true) band!(ax, linepath, linepathh, color = repeat(1:1386, outer=2), transparency=true) image!(ax, -180..180, -90..90, earth_img'[:,end:-1:1]) rotate!(ax.scene, 2*pi/2.6) fig zoom!(ax.scene, cameracontrols(ax.scene), 30) # center!(ax.scene) ``` -------------------------------- ### Create Stem Plot in Julia Source: https://beautiful.makie.org/dev/examples/2d/stem/stem This snippet demonstrates how to create a stem plot using CairoMakie.jl. It includes customizations for color, stem style, and markers, showcasing data visualization capabilities. ```julia using CairoMakie, Random Random.seed!(2) t = 0.3:0.3:3π my_markers = [:circle, :rect, :utriangle, :dtriangle, :diamond, :pentagon, :cross, :xcross] fig, ax, = stem(t, 1.5exp.(-t/5).*cos.(t); color = 1:length(t), colormap = :linear_wyor_100_45_c55_n256, stemcolor = 1:length(t), stemcolormap = :linear_wcmr_100_45_c42_n256, figure = (; size = (600,400))) stem!(t .+ 0.15, -cos.(t) ./ t .+ 0.25; color = :transparent, stemwidth = 0.5, marker = :rect, markersize = 10, strokewidth = 1, strokecolor = :black) stem!(1:8, 1.5randn(8); marker = my_markers, color = tuple.(resample_cmap(:mk_12, 8), 0.65), stemlinestyle = :dash, stemcolor = resample_cmap(:mk_12, 8), markersize = 15*rand(8) .+ 10, strokewidth = 1.5, strokecolor = resample_cmap(:mk_12, 8)) hidedecorations!(ax; grid = false) fig ``` -------------------------------- ### Get Makie Contributor Avatars (Julia) Source: https://beautiful.makie.org/dev/examples/2d/scatters/makie_contributors This function retrieves contributor avatars from the JuliaPlots/Makie.jl GitHub repository. It downloads the avatar images and returns them as an array of loaded images. Dependencies include GLMakie, GitHub, Downloads, and FileIO. ```Julia using GLMakie, GitHub, Downloads, FileIO function getavatars(; n = 90) contri = GitHub.contributors("JuliaPlots/Makie.jl")[1] avatars = [] contributions = [] for i in eachindex(contri) push!(avatars, contri[i]["contributor"].avatar_url.uri) push!(contributions, contri[i]["contributions"]) end p = sortperm(contributions, rev=true) imgs = [] for i in p[1:n] img_d = Downloads.download(avatars[i]) push!(imgs, load(img_d)) end return imgs end avatars = getavatars() ``` -------------------------------- ### Initialize GLMakie and Close Existing Windows Source: https://beautiful.makie.org/dev/examples/3d/meshes/cpunkCube Initializes the GLMakie backend for rendering and closes any previously open visualization windows. This ensures a clean slate for new plots. It requires the GLMakie, FileIO, GeometryBasics, and Downloads packages. ```julia using GLMakie, FileIO using GeometryBasics using Downloads import Cascadia: Selector import Gumbo: parsehtml import HTTP GLMakie.activate!() GLMakie.closeall() # close any open screen ``` -------------------------------- ### Create 3D Surface, Contour, and Wireframe Plot in Makie Source: https://beautiful.makie.org/dev/examples/3d/surfaces/surface This Julia code snippet demonstrates how to create a 3D plot featuring a surface, contour lines, and a wireframe overlay using the GLMakie library. It defines a surface using a mathematical function and then adds contour lines at the base and a wireframe to visualize the surface structure. This requires the GLMakie library to be installed and activated. ```julia using GLMakie GLMakie.activate!() GLMakie.closeall() # close any open screen x = y = LinRange(-2, 2, 51) z = (-x .* exp.(-x .^ 2 .- (y') .^ 2)) .* 4 zmin, zmax = minimum(z), maximum(z) cmap = :viridis fig = Figure(size = (1200, 800), fontsize = 22) ax = Axis3(fig[1, 1], aspect = :data, perspectiveness = 0.5, elevation = π / 9, xzpanelcolor = (:black, 0.75), yzpanelcolor = (:black, 0.75), zgridcolor = :grey, ygridcolor = :grey, xgridcolor = :grey) sm = surface!(ax, x, y, z; colormap = cmap, colorrange = (zmin, zmax), transparency = true) xm, ym, zm = minimum(ax.finallimits[]) contour!(ax, x, y, z; levels = 20, colormap = cmap, linewidth = 2, colorrange = (zmin, zmax), transformation = (:xy, zmin), transparency = true) wireframe!(ax, x, y, z; overdraw = true, transparency = true, color = (:black, 0.1)) Colorbar(fig[1, 2], sm, height = Relative(0.5)) colsize!(fig.layout, 1, Aspect(1, 1.0)) fig ``` -------------------------------- ### Create Filled Gradient under 3D Curve (Julia) Source: https://beautiful.makie.org/dev/examples/3d/lines3d/filled3d_curve This code snippet demonstrates how to create a gradient under a 3D curve using GLMakie. It builds upon the previous example by adding a `band!` function with a colormap applied to the `z` values. The example leverages `Point3f` for 3D coordinates and provides finer control over plot aesthetics. ```julia fig = Figure(; size=(600, 400)) ax = Axis3(fig[1,1]; limits=((0,3), (0,3), (0,0.2)), perspectiveness = 0.5, azimuth = -0.5, elevation = 0.3,) band!(Point3f.(x, y, 0), Point3f.(x, y, z); color = z,\n colormap = (:Spectral, 0.85), transparency=true) lines!(Point3f.(x, y, z); color=(:black, 0.9), transparency=true) fig ``` -------------------------------- ### Download and Load Images from URLs Source: https://beautiful.makie.org/dev/examples/3d/meshes/cpunkCube Downloads images from specified URLs using the Downloads package and loads them using the FileIO package. It then crops the images to a specific size (1000x1000 pixels) for consistency. This is useful for preparing image data for plotting. ```julia lucy = Downloads.download("https://pbs.twimg.com/media/FbbZqWTXkAA8KTo?format=jpg&name=large") lucy = load(lucy) lucy = lucy[1:1000,1:1000]; david = Downloads.download("https://pbs.twimg.com/media/FdGmKklXEAAkdG1?format=jpg&name=large") david = load(david) david = david[1:1000,1:1000]; faraday = Downloads.download("https://pbs.twimg.com/media/Fdq1ev-X0AM-tXv?format=jpg&name=large") faraday = load(faraday) faraday = faraday[1:1000,1:1000]; lucydavid = Downloads.download("https://pbs.twimg.com/media/FdAs55qXoAAyG9l?format=jpg&name=large") lucydavid = load(lucydavid) luda = Downloads.download("https://pbs.twimg.com/media/Fcs-pGSX0AIdzWs?format=jpg&name=large") luda = load(luda) luda = luda[201-40:1240,end:-1:1]; poster = Downloads.download("https://pbs.twimg.com/media/FZFjXDAWIAE-vAT?format=jpg&name=large") poster = load(poster) poster = poster[1+80:1080+80,end:-1:1]; ``` -------------------------------- ### Create Iris Dataset Scatter Plot with Beautiful Makie Source: https://beautiful.makie.org/dev/examples/2d/scatters/iris_dataset This code demonstrates creating a scatter plot visualization of the iris dataset using Beautiful Makie (CairoMakie) in Julia. It loads the iris dataset from RDatasets, creates different markers for each species category, and displays them with randomized colors. The example includes figure setup, axis configuration, data filtering, and legend creation. Dependencies include CairoMakie for plotting, RDatasets for data, Random for seeding, and Colors for color management. ```julia using CairoMakie, RDatasets, Random, Colors Random.seed!(4353) dset = dataset("datasets", "iris") byCat = dset.Species categ = unique(byCat) markers = [:circle, :diamond, :utriangle] fig = Figure(; size=(600, 400), backgroundcolor=:transparent) ax = Axis(fig[1, 1]; xlabel="Sepal Length", ylabel="Sepal Width", backgroundcolor=:transparent) for (idx, c) in enumerate(categ) indices = findall(x -> x == c, byCat) scatter!(dset.SepalLength[indices], dset.SepalWidth[indices]; marker=markers[idx], color = rand(RGBf), markersize=15, label="$(c)") end axislegend("Species") fig ``` -------------------------------- ### Load and Prepare Penguin Data with Julia Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/penguinsBoxes This function loads the Palmer Penguins dataset into a DataFrame and removes rows with missing values. It's a prerequisite for most plotting operations in this example. ```julia using CairoMakie, PalmerPenguins, DataFrames using AlgebraOfGraphics function getPenguins() # ENV["DATADEPS_ALWAYS_ACCEPT"] = "true" penguins = dropmissing(DataFrame(PalmerPenguins.load())) return penguins end penguins = getPenguins() ``` -------------------------------- ### Load and Plot Datasaurus Dozen Data with Makie Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/datasaurus Loads the Datasaurus Dozen dataset from a URL using CSV and Downloads, then visualizes it using AlgebraOfGraphics and CairoMakie. The plot is faceted by dataset and uses a light theme. ```julia using CSV, Downloads, DataFrames using AlgebraOfGraphics, CairoMakie using Statistics #https://github.com/jumpingrivers/datasauRus #https://www.autodesk.com/research/publications/same-stats-different-graphs link = "https://raw.githubusercontent.com/jumpingrivers/datasauRus/main/inst/extdata/DatasaurusDozen-Long.tsv" file = Downloads.download(link) dsaurus = CSV.read(file, DataFrame, delim = '\t') plt = data(dsaurus) * mapping(:x => "", :y => "", layout=:dataset) with_theme(theme_light(), size = (1600,1200), fontsize = 24) do draw(plt) ## palettes = (layout=wrap(cols=3),) end ``` -------------------------------- ### Plot Close Price Line Chart in Julia using Makie Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/MarketData Generates a line plot of the 'Close' price over time using AlgebraOfGraphics and CairoMakie. This example utilizes the ggplot2 theme for styling. ```julia plt = data(cl)*mapping(:timestamp, :Close)*visual(Lines) with_theme(theme_ggplot2(), size = (600,400)) do plt |> draw end ``` -------------------------------- ### Create 3D RGBA cube visualization with GLMakie Source: https://beautiful.makie.org/dev/examples/3d/mscatters/RGBAcube Generates a 3D cube visualization where each cube's position and color (RGBA) are programmatically defined. Uses GLMakie for rendering, GeometryBasics for 3D primitives, and Colors for color handling. Creates 7x7x7 grid of cubes with transparency and custom sizing. ```julia using GLMakie, Colors using GeometryBasics: Rect3f GLMakie.activate!() GLMakie.closeall() # close any open screen positions = vec([Point3f(i / 5, j / 5, k / 5) for i = 1:7, j = 1:7, k = 1:7]) ## note 7 > 5 [factor in each i,j,k], whichs is misleading fig, ax, obj = meshscatter(positions; marker = Rect3f(Vec3f(-0.5), Vec3f(1.8)), transparency = true, color = [RGBA(positions[i]..., 0.5) for i in eachindex(positions)], figure = (; size = (1200, 800)) ) fig ``` -------------------------------- ### Initialize plot theme and figure Source: https://beautiful.makie.org/dev/examples/2d/heatmaps/heatmapScaleSections Sets up the visual theme for the plot and creates a new figure. The theme includes font sizes, colormap selection, and figure dimensions. ```julia theme = Theme(fontsize = 12, colormap = :gist_earth, ; size = (750, 850)) set_theme!(theme) fig = Figure() ``` -------------------------------- ### Apply ggplot2 Theme to Makie Plots Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/datasaurus Applies the ggplot2 theme to a Makie plot, customizing the appearance with a light grey background for plot facets. This example demonstrates theme integration and layout management. ```julia with_theme(theme_ggplot2(), size = (1600,1200), fontsize = 24) do fig = Figure() g = GridLayout(fig[1,1]) wfacet = draw!(g, plt) bxs = [Box(g[i,j, Top()], color = (:grey70, 0.95), strokevisible = false) for i in 1:4 for j in 1:4] [translate!(bxs[i].blockscene, 0,0,-1) for i in 1:15] delete!.(bxs[14:end]) fig end ``` -------------------------------- ### Generate 3D Revolution Surface using GLMakie Source: https://beautiful.makie.org/dev/examples/3d/surfaces/revolution_surface_s Creates a 3D revolution surface visualization from parametric equations using GLMakie. Generates mesh grids for u and v parameters, computes surface coordinates, and renders with advanced shading, colormap, and transparency. Includes wireframe overlay and colorbar for enhanced visualization. ```julia using GLMakie GLMakie.activate!() GLMakie.closeall() # close any open screen u = LinRange(-1.5, 2, 50) v = LinRange(0, 2 * pi, 50) X1 = [u for u in u, v in v] Y1 = [(u^2 + 1) * cos(v) for u in u, v in v] Z1 = [(u^2 + 1) * sin(v) for u in u, v in v] fig, ax, pltobj = surface(X1, Y1, Z1; shading = FastShading, #ambient = Vec3f(0.95, 0.95, 0.95), backlight = 1.0f0, color = sqrt.(X1 .^ 2 .+ Y1 .^ 2 .+ Z1 .^ 2), colormap = :Isfahan2, transparency = true, figure = (; size = (1200, 800), fontsize = 22)) wireframe!(X1, Y1, Z1; linewidth = 0.2, transparency = true) Colorbar(fig[1, 2], pltobj, height = Relative(0.5)) colsize!(fig.layout, 1, Aspect(1, 1.0)) fig ``` -------------------------------- ### Julia Boxplots: Vertical and Horizontal Source: https://beautiful.makie.org/dev/examples/2d/boxplots/vertical_horizontal Generates vertical and horizontal boxplots using CairoMakie in Julia. This example visualizes a normal distribution and showcases customization options for colors, whiskers, and labels. Requires the CairoMakie and Random libraries. ```julia using CairoMakie, Random Random.seed!(13) n = 3000 data_r = randn(n) a = fill(1, n) fig = Figure(size = (600, 400)) ax1 = Axis(fig[1, 1], xlabel = "variable", ylabel = "values", xticks = ([1], ["normal Distribution"])) ax2 = Axis(fig[1, 2], xlabel = "values", ylabel = "variable", yticks = ([1], ["normal Distribution"]), yticklabelrotation = pi / 2) boxplot!(ax1, a, data_r; whiskerwidth = 1, width = 0.35, color = (:red, 0.45), whiskercolor = (:red, 1), mediancolor = :red, markersize = 8, strokecolor = :black, strokewidth = 1, label = "vertical") limits!(ax1, 0, 2, -5, 5) boxplot!(ax2, a, data_r; orientation = :horizontal, whiskerwidth = 1, width = 0.35, color = (:navy, 0.45), whiskercolor = (:navy, 1), mediancolor = :navy, markersize = 8, strokecolor = :black, strokewidth = 1, label = "horizontal") limits!(ax2, -5, 5, 0, 2) axislegend(ax1, position = :rb, framecolor = :transparent) axislegend(ax2, position = :rt, backgroundcolor = (:dodgerblue, 0.2)) fig ``` -------------------------------- ### Create 3D Simplex Visualization with GLMakie Source: https://beautiful.makie.org/dev/examples/3d/meshes/simplex Demonstrates creating a 3D tetrahedron (simplex) visualization using GLMakie. Sets up vertices and faces, creates mesh and poly objects, adds sphere markers at calculated positions, and draws directional arrows. Includes camera controls for rotation and zoom. Requires GLMakie package and Julia environment. ```julia using GLMakie GLMakie.activate!() GLMakie.closeall() # close any open screen vertices = [ 0 0 0 1 0 0 0 1 0 0 0 1 ] _faces = [ 3 2 1 4 1 2 4 3 1 4 2 3 ] # m = GLMakie.GeometryBasics.Mesh(GLMakie.Makie.to_vertices(vertices), GLMakie.Makie.to_triangles(faces)) # mesh(m) marker = Sphere(Point3f(0), 1) # 0 -> -0.5, fully inside, 0 -> 0.5 fully outside fig = Figure(size = (600,600)) ax = LScene(fig[1,1], show_axis=false) m = mesh!(ax, vertices, _faces; color = :white, transparency=true,) poly!(ax, vertices, _faces; color = :transparent, transparency=true, strokewidth = 1.0) meshscatter!(ax, Point3f(1/3, 1/3,1/3), # you need to calculate this for your use case marker = marker, markersize = 0.025, transparency=true) # the following are not over the plane nither perpendicular. arrows!(ax, [Point3f(1/3, 1/3,1/3)], # you need to calculate this for your use case [Point3f(0.2, 0.1,0.3)], # you need to calculate this for your use case arrowsize = Vec3f(0.05, 0.05, 0.08), color = :red, arrowcolor = :black) arrows!(ax, [Point3f(1/3, 1/3,1/3)], # you need to calculate this for your use case [Point3f(-0.1, -0.1,0.3)], # you need to calculate this for your use case arrowsize = Vec3f(0.08, 0.08, 0.08), linewidth = 0.02, color = :dodgerblue, arrowcolor = :orange) zoom!(ax.scene, cameracontrols(ax.scene), 0.9) GLMakie.rotate!(ax.scene, -0.1) fig ``` -------------------------------- ### Generate Julia set visualizations using Makie (Julia) Source: https://beautiful.makie.org/dev/examples/datavis/fractals The snippet computes Julia set fractals for a set of complex constants and visualizes them in a 2x4 grid using Makie's Figure and Axis objects. It relies on the Makie package and the julia_set! function, taking parameters for domain bounds, resolution, and iteration count. The output is a Makie figure displaying heatmaps of the fractal images. ```julia cvalues = [0.274 - 0.008 * 1im, 0.285 + 0.01*1im, -0.70176 - 0.3842*1im, -0.8 + 0.156*1im, -0.7269 + 0.1889*1im, -0.1 + 0.65*1im, -0.382 + 0.618*1im, -0.449 + 0.571*1im] fig = Figure(size=(1200,600)) axs = [Axis(fig[i,j]; aspect = DataAspect()) for i in 1:2 for j in 1:4] npoints = 300 img = zeros(npoints, npoints) for idx in 1:8 julia_set!(img,-1.7, 1.7, -1.7, 1.7, npoints; b=1000, c=cvalues[idx]) heatmap!(axs[idx], log10.(img); colormap=cmaps[idx]) end hidedecorations!.(axs) colgap!(fig.layout, 1) rowgap!(fig.layout,1) hidespines!.(axs) fig ``` -------------------------------- ### Load and prepare penguin data Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/penguins3d Function to load the Palmer Penguins dataset and remove missing values. Depends on PalmerPenguins and DataFrames packages. Returns a cleaned DataFrame for visualization. Requires internet connection for first-time data download. ```julia using PalmerPenguins, DataFrames using AlgebraOfGraphics import AlgebraOfGraphics as AoG using GLMakie GLMakie.activate!() function getPenguins() # ENV["DATADEPS_ALWAYS_ACCEPT"] = "true" penguins = dropmissing(DataFrame(PalmerPenguins.load())) return penguins end penguins = getPenguins() ``` -------------------------------- ### Find Maximum Length Coastline Index (Julia) Source: https://beautiful.makie.org/dev/examples/geo/vertical_feature_mask This snippet, written in Julia, calculates and displays the index of the longest coastline from a GeoMakie dataset. It utilizes the `findmax` function to determine the maximum length and its corresponding index. This is a utility function used in conjunction with other plotting examples. ```julia idx_l = (693, 95) ``` -------------------------------- ### Create and Render 3D Volume Plot in Julia Source: https://beautiful.makie.org/dev/examples/3d/volume/volume Generates a 3D volume plot using Makie. It defines a function to create sample data, then uses the `volume` function to render it. Customizations include color mapping, transparency, and camera angles. ```julia using GLMakie, ColorSchemes GLMakie.activate!() GLMakie.closeall() # close any open screen x = y = z = 1:10 f(x, y, z) = x^2 + y^2 + z^2 vol = [f(ix, iy, iz) for ix in x, iy in y, iz in z] fig, ax, _ = GLMakie.volume(1 .. 10, 1 .. 10, 1 .. 10, vol; colorrange = (minimum(vol), maximum(vol)), colormap = :Egypt, transparency = true, figure = (; size = (1200, 800)), axis = (; type = Axis3, perspectiveness = 0.5, azimuth = 2.19, elevation = 0.57, aspect = (1, 1, 1) ) ) fig ``` -------------------------------- ### Julia: 3x3 Random Matrix Eigenvalue Heatmap Source: https://beautiful.makie.org/dev/examples/datavis/eigenvals_densities This example visualizes the eigenvalue distribution of a 3x3 random matrix. The `m3` function defines the matrix structure. Eigenvalue counts are accumulated using `getcounts!`, equalized via `eq_hist`, and then plotted as a heatmap with the 'CMRmap' colormap. ```julia m3(;a=9rand()-5,b=9rand()-5) = [a 1 -1; -1 b 0; 1 -1 -1] h = HeatMap(range(-4,4,length=1200),range(-2,2,length=1200)) getcounts!(h, m3; n = 500_000) with_theme(theme_dark()) do fig = Figure(figure_padding=0,size=(600,400)) ax = Axis(fig[1,1]; aspect = DataAspect()) heatmap!(ax, -4..4, -2..2,eq_hist(h.counts); colormap = :CMRmap) hidedecorations!(ax) hidespines!(ax) fig end ``` -------------------------------- ### Render 3D Earthquake Visualization on Earth with Makie (Julia) Source: https://beautiful.makie.org/dev/examples/datavis/earthquakes This snippet builds a 3D scene with a textured Earth sphere and scatter points for earthquakes, colored by magnitude and displaced by depth. It includes a colorbar, labels, optional rotation animation, and export to PNG/MP4. Requires network access to download data and a GPU-capable environment for GLMakie. ```julia using CSV, DataFrames using GLMakie, Colors, ColorSchemes using FileIO, Downloads GLMakie.activate!() # Original reference: https://glowy-earthquakes.glitch.me urlimg = "https://upload.wikimedia.org/wikipedia/commons/9/96/NASA_bathymetric_world_map.jpg" earth_img = load(Downloads.download(urlimg)) function sphere(; r = 1.0, n = 32) θ = LinRange(0, π, n) φ = LinRange(-π, π, 2 * n) x = [r * cos(φ) * sin(θ) for θ in θ, φ in φ] y = [r * sin(φ) * sin(θ) for θ in θ, φ in φ] z = [r * cos(θ) for θ in θ, φ in φ] return (x, y, z) end # https://earthquake.usgs.gov/earthquakes/map/?extent=-68.39918,-248.90625&extent=72.60712,110.74219 urldata = "https://raw.githubusercontent.com/MakieOrg/BeautifulMakie/main/data/" file1 = Downloads.download(urldata * "2021_01_2021_05.csv") file2 = Downloads.download(urldata * "2021_06_2022_01.csv") earthquakes1 = CSV.read(file1, DataFrame) earthquakes2 = CSV.read(file2, DataFrame) earthquakes = vcat(earthquakes1, earthquakes2) # depth unit, km function toCartesian(lon, lat; r = 1.02, cxyz = (0, 0, 0)) x = cxyz[1] + (r + 1500_000) * cosd(lat) * cosd(lon) y = cxyz[2] + (r + 1500_000) * cosd(lat) * sind(lon) z = cxyz[3] + (r + 1500_000) * sind(lat) return (x, y, z) ./ 1500_000 end lons, lats = earthquakes.longitude, earthquakes.latitude depth = earthquakes.depth mag = earthquakes.mag toPoints3D = [Point3f([toCartesian(lons[i], lats[i]; r = -depth[i] * 1000)...]) for i in eachindex(lons)] ms = (exp.(mag) .- minimum(exp.(mag))) ./ maximum(exp.(mag) .- minimum(exp.(mag))) with_theme(theme_black()) do fig = Figure(size = (900, 900), fontsize = 20) ax = LScene(fig[1, 1], show_axis = false) pltobj = meshscatter!(ax, toPoints3D; markersize = ms / 20 .+ 0.001, color = mag, colormap = resample_cmap(:afmhot, 256)[10:end], shading = FastShading) surface!(ax, sphere(; r = 1.0)..., color = tuple.(earth_img, 0.1), shading = FastShading, transparency = true) Colorbar(fig[1, 2], pltobj, label = "Magnitude", height = Relative(1.5 / 4)) Label(fig[1, 1, Top()], rich("Visualization by ", rich("Lazaro Alonso\n", color=:dodgerblue), rich("using Makie", color=:orangered)), justification=:left, halign=1.0 ) Label(fig[1, 1, Top()], "Earthquakes on Earth. Jan-2021 to Jan-2022\nOriginal data from USGS", halign=0.0, justification=:left) zoom!(ax.scene, cameracontrols(ax.scene), 0.55) rotate!(ax.scene, 3.0) save("earthquakes.png", fig; update=false) ##run this to get a smooth animation record(fig, "earthquakes.mp4", framerate = 24, update=false) do io for i in 3.0:0.015:9.5 rotate!(ax.scene, i) recordframe!(io) # record a new frame end end end ``` -------------------------------- ### Apply ggplot2 Theme in Makie.jl Source: https://beautiful.makie.org/dev/examples/themes/ggplot2_stem Applies the ggplot2 theme to Makie plots, demonstrating custom markers, colormaps, and stem plot configurations. This example requires the `CairoMakie` and `Random` packages. It generates a figure with multiple stem plots, showcasing different styling options. ```julia using CairoMakie, Random Random.seed!(2) t = 0.3:0.3:3π my_markers = [:circle, :rect, :utriangle, :dtriangle, :diamond, :pentagon, :cross, :xcross] with_theme(theme_ggplot2()) do fig, ax, = stem(t, 1.5exp.(-t/5).*cos.(t); color = 1:length(t), colormap = :linear_wyor_100_45_c55_n256, stemcolor = 1:length(t), stemcolormap = :linear_wcmr_100_45_c42_n256, figure = (; size = (600,400))) stem!(t .+ 0.15, -cos.(t) ./ t .+ 0.25; color = :transparent, stemwidth = 0.5, marker = :rect, markersize = 10, strokewidth = 1, strokecolor = :black) stem!(1:8, 1.5randn(8); marker = my_markers, color = tuple.(resample_cmap(:mk_12, 8), 0.65), stemlinestyle = :dash, stemcolor = resample_cmap(:mk_12, 8), markersize = 15*rand(8) .+ 10, strokewidth = 1.5, strokecolor = resample_cmap(:mk_12, 8)) hidedecorations!(ax; grid = false) fig end ``` -------------------------------- ### Define custom color palette Source: https://beautiful.makie.org/dev/examples/algebra_of_graphics/penguins3d Creates a custom color palette with three colors (grey, orange, dodgerblue) at 50% opacity for consistent visualization styling. Defines both color and patchcolor properties for comprehensive theme support. Used in subsequent plotting examples. ```julia colors = tuple.([:grey10, :orange, :dodgerblue], 0.5) palstyle = (; color=colors, patchcolor = colors); ``` -------------------------------- ### Create Interest Rate Differential Visualization Source: https://beautiful.makie.org/dev/examples/datavis/multipleTitles Generates a multi-series line plot showing interest rate differentials across different regions (Euro, Japan, UK, Emerging markets) using a dark theme. Creates synthetic time series data from 2007-2035, applies data processing with cumulative sums and normalization, and includes significant economic event annotations. The visualization includes custom styling, legend positioning, and comprehensive labeling with data source attribution. ```julia x = range(2007, 2035, length = 1000) function randdata(n) data = cumsum(randn(1000)) data .-= range(first(data), last(data), length = 1000) data .* 0.1 end euro = randdata(1000) japan = randdata(1000) .+ 1 uk = randdata(1000) .- 2 emerging = randdata(1000) .- 6 ``` ```julia with_theme(theme_dark(), size = (650, 450)) do fig = Figure() ax = Axis(fig[1, 1], xgridvisible = false, ygridvisible = false, xticksvisible = false, alignmode = Outside(), xticks = 2007:4:2031, ytrimspine = true, palette = (; color = [:deepskyblue, :firebrick3, :dodgerblue4, :goldenrod1])) hidespines!(ax, :b, :t, :r) hlines!(ax, 0, color = :grey90, linewidth = 1) for (label, data) in ["Euro" => euro, "Japan" => japan, "UK" => uk, "Emerging markets" => emerging] lines!(ax, x, data; label, linewidth = 2) end titlelayout = GridLayout(fig[0, 1], halign = :left, tellwidth = false) Label(titlelayout[1, 1], "Interest rate differentials", halign = :left, fontsize = 30, font="TeX Gyre Heros Bold Makie") Label(titlelayout[2, 1], "Differences in monetary policy are a key driver of the strong dollar.", halign = :left, fontsize = 20) Label(titlelayout[3, 1], "(versus US interest rate, percent)", halign = :left) rowgap!(titlelayout, 0) for (label, (year, y)) in ["Global\nfinancial\ncrisis" => (2008, 8), "Taper\ntantrum" => (2013, 8), "China\n2015\ncrisis" => (2015.4, 6), "Russia invasion\nof Ukraine" => (2022.1, 8)] lines!(ax, [year, year], [-10, y], color = :grey90, linestyle = :dash) text!(ax, year, y, text = label, align = (:left, :top), offset = (10, 0), fontsize = 14) end ylims!(ax, -11, 11) xlims!(ax, 2007, 2035) axislegend(position = (0.5, 1.05), orientation = :horizontal, framevisible = false) Label(fig[2, 1], """ Sources: Bloomberg Finance L.P.; Haver Analytics; and IMF staff calculations. Notes: Differential is calculated as US overnight bank funding rate minus foreign inter-bank rate. The dots depict the forward paths for nominal interest rates. """, tellwidth = false, halign = :left, justification = :left) fig end ``` -------------------------------- ### Julia Imports for Makie Attractors Visualization Source: https://beautiful.makie.org/dev/examples/datavis/strange_attractors Imports necessary packages including GLMakie for interactive plotting, StatsBase and OnlineStats for statistical computations, LinearAlgebra for matrix operations, and Interpolations for data interpolation. Activates GLMakie backend. No inputs or outputs; essential setup for attractor generation and visualization. Limited to Julia ecosystem dependencies. ```julia using GLMakie, StatsBase, OnlineStats using LinearAlgebra, Interpolations GLMakie.activate!() ```