### Gadfly Plot Setup Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/compositing.md Initial setup for Gadfly plots, including importing necessary packages, setting default plot size, and loading the Iris dataset for subsequent examples. ```Julia using Gadfly, RDatasets, Distributions set_default_plot_size(14cm, 8cm) iris = dataset("datasets", "iris") ``` -------------------------------- ### Gadfly.jl Continuous Scale API Reference Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/tutorial.md Reference for continuous scales in Gadfly.jl, detailing the corresponding `Scale`, `Guide`, and `Theme` palette options for various aesthetics like `x`, `y`, `color`, `size`, and `alpha`. It also includes examples of scale formatting and transformations. ```APIDOC Continuous Scales: Aesthetic | Scale. | Guide. | Theme palette ----------|--------------------|------------|--------------------------- x | x_continuous | xticks | y | y_continuous | yticks | color | color_continuous | colorkey | (tbd) size | size_continuous | --- | point_size_min, point_size_max | size_radius | sizekey | continuous_sizemap alpha | alpha_continuous | alphakey | Example Scale Format: Scale.x_continuous(format= , minvalue= , maxvalue= ) `format` can be: `:plain`, `:scientific`, `:engineering`, or `:auto`. Scale Transformations: _sqrt, _log, _log2, _log10, _asinh (for x, y, color aesthetics) _area (for size aesthetic) ``` -------------------------------- ### Enable stacked guides in Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/NEWS.md Enables the functionality for stacked guides within Gadfly.jl. This allows multiple guides to be displayed in a stacked manner, improving layout and information density. ```APIDOC Gadfly.jl API Change: Component: Guides Change: Enabled stacked guides Reference: #1423 ``` -------------------------------- ### Install Gadfly.jl Package Source: https://github.com/giovineitalia/gadfly.jl/blob/master/README.md This snippet demonstrates how to install the Gadfly.jl package using Julia's built-in package manager. Gadfly is registered in Julia's `General` registry, making installation straightforward. ```Julia Pkg.add("Gadfly") ``` -------------------------------- ### Creating Manual Color and Discrete Keys (Gadfly) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/guides.md This example demonstrates the use of `Guide.manual_color_key` and `Guide.manual_discrete_key` to create highly customized legends. It allows specifying legend entries, their corresponding colors or discrete values, and even custom shapes for the legend swatches, providing fine-grained control over legend appearance. ```Julia using DataFrames, Gadfly, RDatasets set_default_plot_size(21cm, 7cm) points = DataFrame(index=rand(0:10,30), val=rand(1:10,30)) line = DataFrame(val=rand(1:10,11), index=collect(0:10)) p1 = plot(layer(points, x=:index, y=:val, color=[colorant"green"]), layer(line, x=:index, y=:val, Geom.line), Guide.manual_color_key("Legend", ["Points", "Line"], ["green", "deepskyblue"], shape=[Shape.circle, Shape.hline])) D = groupby(dataset("COUNT", "titanicgrp"), :Class) fn1(s,c) = 100*s./sum(c) D = combine(D, :Age, :Sex, [:Survive, :Cases]=>fn1=>:prcnt) p2 = plot(stack(D, [:Age, :Sex]), xgroup=:Class, Geom.subplot_grid(layer(x=:variable, y=:prcnt, color=:value, Geom.bar)), Scale.x_discrete, Guide.ylabel("Survival (% Class)"), Guide.manual_color_key("Age", ["children","adults"], 1:2), Guide.manual_color_key("Sex", ["female","male"], 3:4), Theme(bar_spacing=1mm, key_position=:none, key_swatch_shape=Shape.square, point_size=4pt)) hstack(p1, p2) ``` -------------------------------- ### Grid Stack with Blank Panels and Relative Guide Positioning Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/compositing.md Illustrates creating a grid of plots using `gridstack`, including how to leave panels blank with `Geom.blank` and add elements like `Scales` and `Guides` to them. Also demonstrates using relative units from `Compose` for precise guide positioning. ```Julia using Compose set_default_plot_size(21cm, 16cm) fig1c = plot(iris, x=:SepalWidth, color=:Species, Geom.density, Guide.ylabel("density"), Coord.cartesian(xmin=2, xmax=4.5), theme1) fig1d = plot(iris, color=:Species, size=:PetalLength, Geom.blank, Scale.size_area(maxvalue=7), Theme(key_swatch_color="silver"), Guide.colorkey(title="Species", pos=[0.55w,-0.15h]), Guide.sizekey(title="PetalLength (cm)", pos=[0.2w, -0.10h])) gridstack([fig1a fig1c; fig1b fig1d]) ``` -------------------------------- ### Customizing Size Legends (Gadfly) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/guides.md This example illustrates how to add and customize size legends using `Guide.sizekey`. It demonstrates mapping a discrete variable to point sizes, defining a size mapping function, and customizing the legend's title and position, along with other plot themes. ```Julia using Compose, Gadfly, RDatasets set_default_plot_size(14cm, 8cm) D = groupby(dataset("datasets", "Titanic"), :Class) Titanic = combine(D, :, :Freq=>(c->100*c./sum(c))=>:prcnt) filter!(:Survived=>x->x=="Yes", Titanic) sizemap = n->range(3pt, 8pt, length=n) plot(Titanic, Scale.x_log10, Scale.y_log10, x=:Freq, y=:prcnt, color=:Age, shape=:Sex, size=:Class, Scale.size_discrete2(sizemap), Guide.sizekey(title="Passenger\n Class"), Guide.colorkey(pos=[0.1, -0.3h]), Guide.shapekey(pos=[0.5, -0.31h]), Guide.ylabel("% of Passenger Class"), Theme(discrete_highlight_color=identity, alphas=[0.1], key_swatch_color="grey", key_swatch_shape=Shape.circle, point_size=3pt) ) ``` -------------------------------- ### Install Cairo and Fontconfig for Gadfly Backends Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/backends.md To enable rendering plots to PNG, PDF, PS, and PGF formats, install the Cairo and Fontconfig Julia packages. These packages provide necessary bindings for the cairo and fontconfig libraries, which are required by Gadfly. ```julia Pkg.add("Cairo") Pkg.add("Fontconfig") ``` -------------------------------- ### Customizing Plot Guides with Multiple Layers Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/compositing.md Extends the multi-layer plot example by explicitly adding `Guide` objects for axis labels, a title, and a manual color key. This demonstrates how to override default axis labeling when multiple layers are present. ```Julia plot(iris, layer(x=:SepalLength, y=:SepalWidth), layer(x=:PetalLength, y=:PetalWidth, color=[colorant"red"]), Guide.xlabel("length"), Guide.ylabel("width"), Guide.title("Iris data"), Guide.manual_color_key("",["Sepal","Petal"], [Gadfly.current_theme().default_color,"red"])) ``` -------------------------------- ### Importing Gadfly and Core Dependencies Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/dev/pipeline.md Initial setup for Gadfly plots, importing necessary libraries like DataFrames, Colors, Compose, RDatasets, Showoff, and Gadfly itself to enable plotting functionalities. ```julia using DataFrames using Colors using Compose using RDatasets using Showoff using Gadfly ``` -------------------------------- ### Add Guide.sizekey Source: https://github.com/giovineitalia/gadfly.jl/blob/master/NEWS.md Adds `Guide.sizekey` to Gadfly.jl, providing a dedicated guide for interpreting size aesthetics in plots. This improves the readability and understanding of size-encoded data. ```APIDOC Gadfly.jl API Change: Component: Guide Change: Added sizekey Reference: #1379 ``` -------------------------------- ### Customizing X and Y Axis Labels (Gadfly) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/guides.md This example shows how to set custom labels for the X and Y axes using `Guide.xlabel` and `Guide.ylabel`. It demonstrates options for label orientation (horizontal or vertical) and how to hide a label by passing `nothing`. ```Julia using Gadfly set_default_plot_size(21cm, 8cm) p1 = plot(cos, 0, 2π, Guide.xlabel("Angle")); p2 = plot(cos, 0, 2π, Guide.xlabel("Angle", orientation=:vertical)); p3 = plot(cos, 0, 2π, Guide.xlabel(nothing)); hstack(p1,p2,p3) ``` -------------------------------- ### Install Dependencies for Figure Comparison Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/dev/regression.md Add necessary Julia packages required by the `compare_examples.jl` script. `ArgParse` is essential, and `Cairo`, `Fontconfig`, `Rsvg`, and `Images` are needed for black and white difference highlighting. ```Julia Pkg.add("ArgParse") Pkg.add("Cairo") Pkg.add("Fontconfig") Pkg.add("Rsvg") Pkg.add("Images") ``` -------------------------------- ### Discrete Scales Aesthetic Mappings Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/tutorial.md Mapping of aesthetic properties to their corresponding discrete scales, guides, and theme palettes in Gadfly. This table outlines how different visual elements are controlled by discrete scales. ```APIDOC | Aesthetic | Scale. | Guide. | Theme palette | |-----------|------------------|-------|-----------------| | `x` | `x_discrete` | `xticks` | | | `y` | `y_discrete` | `yticks` | | | `color` | `color_discrete` | `colorkey` | (tbd) | | `shape` | `shape_discrete` | `shapekey` | `point_shapes` | | `size` | `size_discrete` | --- | `point_size_min`, `point_size_max` | | | `size_discrete2`| `sizekey` | `discrete_sizemap` | | `linestyle` | `linestyle_discrete` | linekey (tbd) | `line_style` | | `alpha` | `alpha_discrete` | alphakey (tbd) | `alphas` | | `group` | `group_discrete` | | | | `xgroup` | `xgroup` | | | | `ygroup` | `ygroup` | | | e.g. `Scale.shape_discrete(labels= , levels= , order= )` ``` -------------------------------- ### Gadfly Default Inference for Scales and Guides Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/tutorial.md Gadfly automatically infers appropriate scales and guides when not explicitly provided. This includes continuous and discrete scales for axes, coordinate systems, and guide elements like axis ticks and labels. ```APIDOC Scale.x_discrete Scale.x_continuous Scale.y_continuous Coord.cartesian Guide.xticks Guide.xlabel ``` -------------------------------- ### Creating QQ Plots with Stat.qq in Gadfly (Julia) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/statistics.md This example explains how to generate Quantile-Quantile (QQ) plots using Stat.qq to compare sample distributions against theoretical distributions or other sample distributions. It provides examples for comparing multiple samples to one distribution and one sample to multiple distributions, aiding in normality assessment. ```Julia using Distributions, Gadfly, RDatasets set_default_plot_size(21cm, 8cm) iris, geyser = dataset.("datasets", ["iris", "faithful"]) df = combine(groupby(iris, :Species), :SepalLength=>(x->fit(Normal, x))=>:d) ds2 = fit.([Normal, Uniform], [geyser.Eruptions]) yeqx(x=4:6) = layer(x=x, Geom.abline(color="gray80")) xylabs = [Guide.xlabel("Theoretical q"), Guide.ylabel("Sample q")] p1 = plot(df, x=:d, y=iris[:,1], color=:Species, Stat.qq, yeqx(4:8), xylabs..., Guide.title("3 Samples, 1 Distribution")) p2 = plot(geyser, x=ds2, y=:Eruptions, color=["Normal","Uniform"], Stat.qq, yeqx(0:6), xylabs..., Guide.title("1 Sample, 2 Distributions"), Theme(discrete_highlight_color=c->nothing, alphas=[0.5], point_size=2pt) ) hstack(p1, p2) ``` -------------------------------- ### Install Gadfly.jl using Julia Package Manager Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/index.md Provides the Julia REPL command to add Gadfly.jl to your Julia environment. This uses the built-in package manager to handle dependencies. ```julia julia> ]add Gadfly ``` -------------------------------- ### Add Guide.manual_discrete_key and update Guide.manual_color_key Source: https://github.com/giovineitalia/gadfly.jl/blob/master/NEWS.md Introduces `Guide.manual_discrete_key` and updates `Guide.manual_color_key`. These changes enhance the flexibility and control over manual discrete and color keys in plot guides. ```APIDOC Gadfly.jl API Change: Component: Guide Change: Added manual_discrete_key; updated manual_color_key Reference: #1441 ``` -------------------------------- ### Customizing X and Y Axis Ticks (Gadfly) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/guides.md These examples illustrate how to set custom tick marks for the X and Y axes using `Guide.xticks` and `Guide.yticks`. It covers specifying exact tick positions, hiding tick labels, and changing the orientation of the tick labels. ```Julia using Gadfly set_default_plot_size(21cm, 8cm) ticks = [0.1, 0.3, 0.5] p1 = plot(x=rand(10), y=rand(10), Geom.line, Guide.xticks(ticks=ticks)) p2 = plot(x=rand(10), y=rand(10), Geom.line, Guide.xticks(ticks=ticks, label=false)) p3 = plot(x=rand(10), y=rand(10), Geom.line, Guide.xticks(ticks=ticks, orientation=:vertical)) hstack(p1,p2,p3) ``` ```Julia using Gadfly set_default_plot_size(14cm, 8cm) plot(x=rand(1:10, 10), y=rand(1:10, 10), Geom.line, Guide.xticks(ticks=1:9)) ``` -------------------------------- ### Incrementally Adding Layers and Guides to a Gadfly Plot Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/plotting.md This snippet illustrates how to build a Gadfly plot incrementally using the `push!` function. It starts with an empty plot and then adds a data layer with specific aesthetics, defines a Cartesian coordinate system, and finally sets a title for the plot. ```julia p = plot() push!(p, layer(x=[2,4], y=[2,4], size=[1.4142], color=[colorant"gold"])) push!(p, Coord.cartesian(fixed=true)) push!(p, Guide.title("My Awesome Plot")) ``` -------------------------------- ### Customizing Color Legends (Gadfly) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/guides.md These examples illustrate how to add and customize color legends using `Guide.colorkey`. It shows how to set a legend title, define custom labels for discrete color mappings, and adjust the legend's position within or outside the plot area. ```Julia using Gadfly, RDatasets set_default_plot_size(14cm, 8cm) Dsleep = dataset("ggplot2", "msleep")[:,[:Vore,:BrainWt,:BodyWt,:SleepTotal]] DataFrames.dropmissing!(Dsleep) Dsleep.SleepTime = Dsleep.SleepTotal .> 8 plot(Dsleep, x=:BodyWt, y=:BrainWt, Geom.point, color=:SleepTime, Guide.colorkey(title="Sleep", labels=[">8","≤8"]), Scale.x_log10, Scale.y_log10 ) ``` ```Julia using Gadfly, Compose, RDatasets set_default_plot_size(21cm, 8cm) iris = dataset("datasets","iris") pa = plot(iris, x=:SepalLength, y=:PetalLength, color=:Species, Geom.point, Theme(key_position=:inside) ) pb = plot(iris, x=:SepalLength, y=:PetalLength, color=:Species, Geom.point, Guide.colorkey(title="Iris", pos=[0.05w,-0.28h]) ) hstack(pa, pb) ``` -------------------------------- ### Create a Basic Plot with Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/README.md This example shows how to quickly generate a simple plot using Gadfly.jl. It demonstrates importing the library and creating a plot with a basic set of y-coordinates, illustrating the ease of use for basic visualization tasks. ```Julia using Gadfly plot(y=[1,2,3]) ``` -------------------------------- ### Example Plotting with Gadfly Functions Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/plotting.md This example demonstrates the practical application of Gadfly's plotting functions. It shows how to plot single or multiple functions (e.g., sine, cosine), a 2D expression, and a matrix, then combine the resulting plots horizontally for comparison. ```julia p1 = plot([sin,cos], 0, 2pi) p2 = plot((x,y)->sin(x)+cos(y), 0, 2pi, 0, 2pi) p3 = spy(ones(33)*sin.(0:(pi/16):2pi)' + cos.(0:(pi/16):2pi)*ones(33)') hstack(p1,p2,p3) ``` -------------------------------- ### Comprehensive Plot Specification with Explicit Elements Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/dev/pipeline.md Illustrates a comprehensive Gadfly plot specification, including explicit layers, continuous and discrete scales, Cartesian coordinates, and custom axis guides and color keys. This example shows how to fully control plot elements beyond default inferences, providing fine-grained customization. ```julia p = plot(layer(df, x = :Price, color = :Cut, Stat.histogram, Geom.bar), Scale.x_continuous, Scale.color_discrete, Coord.cartesian, Guide.xticks, Guide.yticks, Guide.xlabel("Price"), Guide.colorkey(title="Cut")) ``` -------------------------------- ### Creating Bar Charts with Geom.bar in Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/geometries.md Shows various ways to create bar charts using `Geom.bar`. The first example demonstrates styling with `alpha` and `position=:identity` for overlapping bars. The second example illustrates `position=:dodge` for grouped bars and `position=:stack` for stacked bars, along with manual color scaling. ```Julia using ColorSchemes, DataFrames, Distributions, Gadfly set_default_plot_size(21cm, 8cm) x = range(-4, 4, length=30) fn1(μ,x=x) = pdf.(Normal(μ, 1), x) D = [DataFrame(x=x, y=fn1(μ), μ="$(μ)") for μ in [-1, 1]] cpalette(p) = get(ColorSchemes.viridis, p) p1 = plot(D[1], y=:y, x=:x, color=0:29, Geom.bar, Scale.color_continuous(colormap=cpalette), Theme(bar_spacing=-0.2mm, key_position=:none)) p2 = plot(D[1], x=:x, y=:y, Geom.bar, alpha=range(0.2,0.9, length=30)) p3 = plot(vcat(D...), x=:x, y=:y, color=:μ, alpha=[0.5], Geom.bar(position=:identity)) hstack(p1, p2, p3) ``` ```Julia using Gadfly, RDatasets, DataFrames set_default_plot_size(21cm, 8cm) hecolor = dataset("datasets","HairEyeColor") D = combine(groupby(hecolor, [:Eye,:Sex]), :Freq=>sum=>:Frequency) p1 = plot(D, color=:Eye, y=:Frequency, x=:Sex, Geom.bar(position=:dodge)) palette = ["brown","blue","tan","green"] # Is there a hazel color? p2a = plot(D, x=:Sex, y=:Frequency, color=:Eye, Geom.bar(position=:stack), Scale.color_discrete_manual(palette...)); p2b = plot(D, x=:Sex, y=:Frequency, color=:Eye, Geom.bar(position=:stack), Scale.color_discrete_manual(palette[4:-1:1]..., order=[4,3,2,1])); hstack(p1, p2a, p2b) ``` -------------------------------- ### Plotting with Scale.color_continuous Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/scales.md Demonstrates `Scale.color_continuous` for mapping continuous data to color. The first example shows basic usage and setting `minvalue`/`maxvalue`. The second example illustrates custom colormaps using `lab_gradient` and anonymous functions for RGB color generation. ```Julia using Gadfly set_default_plot_size(21cm, 8cm) xdata, ydata, cdata = rand(12), rand(12), rand(12) p1 = plot(x=xdata, y=ydata, color=cdata) p2 = plot(x=xdata, y=ydata, color=cdata, Scale.color_continuous(minvalue=-1, maxvalue=1)) hstack(p1,p2) ``` ```Julia using Gadfly, Colors set_default_plot_size(21cm, 8cm) x = repeat((1:10).-0.5, inner=[10]) y = repeat((1:10).-0.5, outer=[10]) p1 = plot(x=x, y=y, color=x+y, Geom.rectbin, Scale.color_continuous(colormap=p->RGB(0,p,0))) p2 = plot(x=x, y=y, color=x+y, Geom.rectbin, Scale.color_continuous(colormap=Scale.lab_gradient("green", "white", "red"))) p3 = plot(x=x, y=y, color=x+y, Geom.rectbin, Scale.color_continuous(colormap=p->RGB(0,p,0), minvalue=-20)) hstack(p1,p2,p3) ``` -------------------------------- ### Adding a Plot Title (Gadfly) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/guides.md This snippet demonstrates the straightforward way to add a main title to a plot using `Guide.title`. It takes a string argument for the title text, which is then displayed prominently above the plot. ```Julia using Gadfly, RDatasets set_default_plot_size(14cm, 8cm) plot(dataset("ggplot2", "diamonds"), x="Price", Geom.histogram, Guide.title("Diamond Price Distribution")) ``` -------------------------------- ### Customize Subplot Grid Guides and Scales Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/compositing.md Illustrates how to apply custom guides and scales within `Geom.subplot_grid` for individual subplots, and how to apply them to the overall plot. Shows horizontal bar charts with stacked positions and custom color palettes for grouped data. ```Julia haireye = dataset("datasets", "HairEyeColor") palette = ["brown", "blue", "tan", "green"] plot(haireye, y=:Sex, x=:Freq, color=:Eye, ygroup=:Hair, Geom.subplot_grid(Geom.bar(position=:stack, orientation=:horizontal), Guide.ylabel(orientation=:vertical) ), Scale.color_discrete_manual(palette...), Guide.colorkey(title="Eye\ncolor"), Guide.ylabel("Hair color"), Guide.xlabel("Frequency") ) ``` -------------------------------- ### Visualize Probability Distributions with Stat.unidistribution in Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/statistics.md Shows how to plot univariate probability distributions using `Stat.unidistribution`. The example demonstrates plotting Normal distributions as lines and ribbons, with options for coloring by group or applying specific confidence intervals. ```Julia using DataFrames, Gadfly, Distributions using Gadfly: w,h set_default_plot_size(21cm, 8cm) D = DataFrame(Dist=["Prior", "Posterior"], Density=[Normal(-0.22, 0.02), Normal(-0.29, 0.015)]) xcoord = Coord.cartesian(xmin=-0.4, xmax=-0.1) gck = Guide.colorkey(title="", pos=[0.5w, -0.4h]) p1 = plot(D, y=:Density, color=:Dist, Guide.title("color=:Dist"), gck, layer(Stat.unidistribution, Geom.line, Geom.ribbon, alpha=[0.8]), xcoord) p2 = plot(D, y=:Density, color=:Dist, layer(Stat.unidistribution, Geom.line), layer(Stat.unidistribution([[0.0001, 0.05], [0.95, 0.9999]]), Geom.ribbon), Guide.ylabel(nothing), Guide.title("color=:Dist"), gck) p3 = plot(D, y=:Density, group=:Dist, xcoord, gck, layer(Stat.unidistribution([[0.0001, 0.1],[0.1, 0.9], [0.9, 0.9999]]), Geom.ribbon, alpha=[0.8]), Scale.color_discrete_manual("orange", "yellow", "coral"), Theme(lowlight_color=identity), Guide.title("group=:Dist"), Guide.ylabel(nothing) ) hstack(p1, p2, p3) ``` -------------------------------- ### Visualizing Density with Stat.density in Gadfly (Julia) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/statistics.md This example illustrates plotting parametric probability density functions (PDFs) and kernel density estimates using Stat.density. It shows how to compare theoretical distributions with empirical data distributions, providing insights into data shape. ```Julia using DataFrames, Gadfly, Distributions set_default_plot_size(21cm, 8cm) x = -4:0.1:4 Da = [DataFrame(x=x, ymax=pdf.(Normal(μ),x), u="μ=$μ") for μ in [-1,1]] Db = [DataFrame(x=randn(200).+μ, u="μ=$μ") for μ in [-1,1]] p1 = plot(vcat(Da...), x=:x, y=:ymax, ymin=[0.0], ymax=:ymax, color=:u, Geom.line, Geom.ribbon, Guide.ylabel("Density"), Theme(alphas=[0.6]), Guide.colorkey(title="", pos=[2.5,0.6]), Guide.title("Parametric PDF") ) p2 = plot(vcat(Db...), x=:x, color=:u, Theme(alphas=[0.6]), Stat.density(bandwidth=0.5), Geom.polygon(fill=true, preserve_order=true), Coord.cartesian(xmin=-4, xmax=4, ymin=0, ymax=0.4), Guide.colorkey(title="", pos=[2.5,0.6]), Guide.title("Kernel PDF") ) hstack(p1,p2) ``` -------------------------------- ### Plotting with Scale.alpha_discrete Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/scales.md Illustrates the use of `Scale.alpha_discrete` to map discrete data to the alpha (transparency) aesthetic. It also includes an example of `Scale.color_discrete` and demonstrates setting up plots with `DataFrames` and `Coord.cartesian`. ```Julia using DataFrames, Gadfly set_default_plot_size(21cm, 8cm) D = DataFrame(x=1:6, y=rand(6), Shape=repeat(["a","b","c"], outer=2)) coord = Coord.cartesian(xmin=0, xmax=7, ymin=0, ymax=1.0) p1 = plot(D, x=:x, y=:y, color=:x, coord, Scale.color_discrete, Geom.point, Geom.hair, Guide.title("Scale.color_discrete, Theme(alphas=[0.5])"), Theme(alphas=[0.5], discrete_highlight_color=identity, point_size=2mm) ) p2 = plot(D, x=:x, y=:y, alpha=:x, shape=:Shape, coord, Scale.alpha_discrete, Geom.point, Geom.hair, Guide.title("Scale.alpha_discrete, Theme(default_color=\"green\")"), Theme(default_color="green", discrete_highlight_color=c->"gray", point_size=2mm, alphas=[0.0,0.2,0.4,0.6,0.8,1.0]) ) hstack(p1,p2) ``` -------------------------------- ### Creating Histograms with Geom.histogram in Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/geometries.md This example showcases various ways to create histograms using Geom.histogram in Gadfly.jl. It covers basic histograms, histograms with specified bin counts, density histograms overlaid with theoretical distributions, and identity-positioned histograms with opacity. ```Julia using Distributions, Gadfly, RDatasets set_default_plot_size(21cm, 16cm) D = dataset("ggplot2","diamonds") gamma = Gamma(2, 2) Dgamma = DataFrame(x=rand(gamma, 10^4)) p1 = plot(D, x="Price", color="Cut", Geom.histogram) p2 = plot(D, x="Price", color="Cut", Geom.histogram(bincount=30)) p3 = plot(Dgamma, Coord.cartesian(xmin=0, xmax=20), layer(x->pdf(gamma, x), 0, 20, color=[colorant"black"]), layer(x=:x, Geom.histogram(bincount=20, density=true, limits=(min=0,)), color=[colorant"bisque"])) a = repeat([0.75, 0.85], outer=40) # opacity D2 = [DataFrame(x=rand(Normal(μ,1), 500), μ="$(μ)") for μ in [-1, 1]] p4 = plot(vcat(D2...), x=:x, color=:μ, alpha=[a;a], Geom.histogram(position=:identity, bincount=40, limits=(min=-4, max=4)), Scale.color_discrete_manual("skyblue","moccasin") ) gridstack([p1 p2; p3 p4]) ``` -------------------------------- ### Plotting Time Series Data with Gadfly Defaults Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/tutorial.md Shows how Gadfly automatically infers scales and guides for a time series plot when not explicitly provided. It plots gasoline consumption per car over years, colored by country, using point and line geometries. ```Julia set_default_plot_size(14cm, 8cm) # hide gasoline = dataset("Ecdat", "Gasoline") plot(gasoline, x=:Year, y=:LGasPCar, color=:Country, Geom.point, Geom.line) ``` -------------------------------- ### Creating Line Plots with Gadfly.jl Geom.line Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/geometries.md Illustrates how to generate line plots using `Geom.line`. Examples show basic line plotting from a dataset and creating multiple colored lines based on a categorical variable. ```Julia using Gadfly, RDatasets set_default_plot_size(21cm, 8cm) p1 = plot(dataset("lattice", "melanoma"), x="Year", y="Incidence", Geom.line) p2 = plot(dataset("Zelig", "approval"), x="Month", y="Approve", color="Year", Geom.line) hstack(p1,p2) ``` -------------------------------- ### Plotting with Scale.color_discrete_manual Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/scales.md Demonstrates `Scale.color_discrete_manual` for assigning specific colors to discrete data points. The second example shows how to use `combine` and `groupby` with `Geom.bar(position=:stack)` and control the order of manually assigned colors. ```Julia using Gadfly, Random Random.seed!(12345) set_default_plot_size(14cm, 8cm) plot(x=rand(12), y=rand(12), color=repeat(["a","b","c"], outer=[4]), Scale.color_discrete_manual("red","purple","green")) ``` ```Julia using Gadfly, RDatasets, DataFrames set_default_plot_size(14cm, 8cm) hecolor = dataset("datasets","HairEyeColor") D = combine(groupby(hecolor, [:Eye,:Sex]), :Freq=>sum=>:Frequency) palette = ["brown","blue","tan","green"] # Is there a hazel color? pa = plot(D, x=:Sex, y=:Frequency, color=:Eye, Geom.bar(position=:stack), Scale.color_discrete_manual(palette...)) pb = plot(D, x=:Sex, y=:Frequency, color=:Eye, Geom.bar(position=:stack), Scale.color_discrete_manual(palette[4:-1:1]..., order=[4,3,2,1])) hstack(pa,pb) ``` -------------------------------- ### Creating Step Plots with Gadfly.jl's Geom.step Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/geometries.md Shows a basic example of how to use Geom.step to generate a step plot. It takes random x and y data points and connects them with horizontal and vertical lines, creating a staircase-like visualization. ```Julia using Gadfly, Random set_default_plot_size(14cm, 8cm) Random.seed!(1234) plot(x=rand(25), y=rand(25), Geom.step) ``` -------------------------------- ### Generating Hexagonal Bin Plots with Geom.hexbin in Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/geometries.md This example demonstrates how to create hexagonal bin plots using Geom.hexbin in Gadfly.jl. It visualizes the density of a 2D dataset, showing how to use default binning and how to specify custom bin counts for more granular control. ```Julia using Gadfly, Distributions set_default_plot_size(21cm, 8cm) X = rand(MultivariateNormal([0.0, 0.0], [1.0 0.5; 0.5 1.0]), 10000); p1 = plot(x=X[1,:], y=X[2,:], Geom.hexbin) p2 = plot(x=X[1,:], y=X[2,:], Geom.hexbin(xbincount=100, ybincount=100)) hstack(p1,p2) ``` -------------------------------- ### Generating Scatter Plots with Gadfly.jl Geom.point Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/geometries.md Provides examples of creating scatter plots using `Geom.point`. It shows how to map data variables to color and shape aesthetics, and how to combine multiple layers or datasets on a single plot. ```Julia using Gadfly, RDatasets set_default_plot_size(21cm, 12cm) D = dataset("datasets", "iris") p1 = plot(D, x="SepalLength", y="SepalWidth", Geom.point); p2 = plot(D, x="SepalLength", y="SepalWidth", color="PetalLength", Geom.point); p3 = plot(D, x="SepalLength", y="SepalWidth", color="Species", Geom.point); p4 = plot(D, x="SepalLength", y="SepalWidth", color="Species", shape="Species", Geom.point); gridstack([p1 p2; p3 p4]) ``` ```Julia using Gadfly, RDatasets set_default_plot_size(14cm, 8cm) plot(dataset("lattice", "singer"), x="VoicePart", y="Height", Geom.point) ``` ```Julia using Gadfly, Distributions set_default_plot_size(14cm, 8cm) rdata = rand(MvNormal([0,0.],[1 0;0 1.]),100) bdata = rand(MvNormal([1,0.],[1 0;0 1.]),100) plot(layer(x=rdata[1,:], y=rdata[2,:], color=[colorant"red"], Geom.point), layer(x=bdata[1,:], y=bdata[2,:], color=[colorant"blue"], Geom.point)) ``` -------------------------------- ### Gadfly Plotting API Concepts and Rendering Pipeline Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/dev/pipeline.md Detailed overview of key Gadfly API components and the step-by-step rendering pipeline. It covers plot specification elements like data sources, geometries, mappings, statistics, coordinates, scales, and guides, and explains how these elements are processed during plot generation. ```APIDOC Plot Specification Elements: - Data Source: e.g., dataset("ggplot2", "diamonds") - Geometry: e.g., Geom.point, Geom.line, Geom.bar - Mappings: Associate aesthetics (e.g., :color) with data elements (e.g., :Cut) - Statistics (layer-wise): e.g., Stat.histogram - Coordinates: e.g., Coord.cartesian, Coord.polar - Scales: e.g., Scale.x_continuous, Scale.color_discrete, Scale.loglog - Statistics (plot-wise): Applied to all layers - Guides: e.g., Guide.xticks, Guide.yticks, Guide.xlabel, Guide.colorkey Rendering Pipeline Steps: 1. Data Mapping: Subsets of data source mapped to Data object (e.g., :Price to :x, :Cut to :color). 2. Scale Application: Scales transform data to plottable aesthetics. - Scale.x_continuous: Keeps values unchanged. - Scale.color_discrete_hue: Maps unique elements to color values. 3. Statistics Transformation: Layer-wise and plot-wise statistics applied. - Stat.histogram: Replaces x field with bin positions, sets y with counts. 4. Coordinate System Creation: Compose context created to fit data to screen coordinates. - Coord.cartesian: Maps vertical distance to screen inches. 5. Geometry Rendering: Each layer renders its own geometry. 6. Guide Layout & Rendering: Guides computed and rendered on top of plot context. ``` -------------------------------- ### Manage Themes with push_theme and pop_theme in Gadfly Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/themes.md This example illustrates how to manage themes using Gadfly's theme stack. `push_theme` adds a new theme to the stack, making it active, while `pop_theme` removes the topmost theme, reverting to the previous one. This allows for setting a theme for multiple plots and then easily restoring the prior state. ```Julia latex_fonts = Theme(major_label_font="CMU Serif", major_label_font_size=16pt, minor_label_font="CMU Serif", minor_label_font_size=14pt, key_title_font="CMU Serif", key_title_font_size=12pt, key_label_font="CMU Serif", key_label_font_size=10pt) Gadfly.push_theme(latex_fonts) gasoline = dataset("Ecdat", "Gasoline") p = plot(gasoline, x=:Year, y=:LGasPCar, color=:Country, Geom.point, Geom.line) # can plot more plots here... Gadfly.pop_theme() p # hide ``` -------------------------------- ### Customize Continuous X-Axis Scales in Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/scales.md This example showcases `Scale.x_continuous` in Gadfly.jl for customizing the continuous x-axis. It demonstrates setting min/max values, applying scientific notation formatting, and using a custom label formatting function with `sprintf`. ```Julia using Gadfly, Random, Printf set_default_plot_size(21cm, 8cm) Random.seed!(1234) p1 = plot(x=rand(10), y=rand(10), Scale.x_continuous(minvalue=-10, maxvalue=10)) p2 = plot(x=rand(10), y=rand(10), Scale.x_continuous(format=:scientific)) p3 = plot(x=rand(10), y=rand(10), Scale.x_continuous(labels=x -> @sprintf("%0.4f", x))) hstack(p1,p2,p3) ``` -------------------------------- ### Plotting with Scale.color_discrete_hue Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/scales.md Shows how to use `Scale.color_discrete` to map discrete data to color, specifically demonstrating a custom color generation function (`gen_colors`) using `distinguishable_colors` for improved visual separation. The second example provides a basic application of `Scale.color_discrete`. ```Julia using Gadfly, Colors, RDatasets, Random set_default_plot_size(14cm, 8cm) Random.seed!(1234) function gen_colors(n) cs = distinguishable_colors(n, [colorant"#FE4365", colorant"#eca25c"], lchoices = Float64[58, 45, 72.5, 90], transform = c -> deuteranopic(c, 0.1), cchoices = Float64[20,40], hchoices = [75,51,35,120,180,210,270,310]) convert(Vector{Color}, cs) end iris = dataset("datasets", "iris") plot(iris, x=:SepalLength, y=:SepalWidth, color=:Species, Geom.point, Scale.color_discrete(gen_colors)) ``` ```Julia using Gadfly, Random set_default_plot_size(21cm, 8cm) Random.seed!(1234) xdata, ydata = rand(12), rand(12) p1 = plot(x=xdata, y=ydata, color=repeat([1,2,3], outer=[4])) p2 = plot(x=xdata, y=ydata, color=repeat([1,2,3], outer=[4]), Scale.color_discrete) hstack(p1,p2) ``` -------------------------------- ### Plotting Rectangles and Rectangular Bins with Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/geometries.md Shows how to create plots using `Geom.rect` for arbitrary rectangles defined by `xmin`, `ymin`, `xmax`, `ymax` and `Geom.rectbin` for binned rectangular data. Examples demonstrate mapping color and alpha to data variables. ```Julia using Gadfly, DataFrames set_default_plot_size(21cm, 8cm) x1, y1, w1 = 0.5:10, rand(10), 0.09.+0.4*rand(10) D = DataFrame(x=x1, y=rand(x1, 10), y1=y1, x2=x1.+w1, y2=y1.+w1, c=0:9) p1 = plot(D, xmin=:x, ymin=:y1, xmax=:x2, ymax=:y2, color=[colorant"green"], alpha=1:10, Geom.rect, Scale.alpha_discrete) p2 = plot(D, xmin=:x, ymin=:y1, xmax=:x2, ymax=:y2, color=:c, alpha=[0.7], Geom.rect, Guide.ylabel(nothing)) p3 = plot(D, x=:x, y=:y, color=:c, alpha=[0.5], Geom.rectbin, Scale.color_discrete) hstack(p1, p2, p3) ``` ```Julia using Gadfly, DataFrames, RDatasets set_default_plot_size(14cm, 8cm) plot(dataset("Zelig", "macro"), x="Year", y="Country", color="GDP", Geom.rectbin) ``` -------------------------------- ### Render Plot to PDF File Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/backends.md Gadfly makes it easy to switch between different rendering backends. This example shows how to save a plot 'p' as a PDF file named 'foo.pdf' by simply replacing 'SVG' with 'PDF' in the function chaining syntax. Other backends like PNG, PS, or PGF can be used similarly. ```julia p |> PDF("foo.pdf") ``` -------------------------------- ### Customizing Shape Legends (Gadfly) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/guides.md This snippet demonstrates how to add and customize shape legends using `Guide.shapekey`. It shows how to map data to different point shapes, set a legend title, define custom labels for the shapes, and customize the appearance of the legend swatches. ```Julia using Compose, Gadfly, RDatasets set_default_plot_size(16cm, 8cm) Dsleep = dataset("ggplot2", "msleep") Dsleep = dropmissing!(Dsleep[:,[:Vore, :Name,:BrainWt,:BodyWt, :SleepTotal]]) Dsleep.SleepTime = Dsleep.SleepTotal .> 8 plot(Dsleep, x=:BodyWt, y=:BrainWt, Geom.point, color=:Vore, shape=:SleepTime, Scale.x_log10, Scale.y_log10, Guide.colorkey, Guide.shapekey(title="Sleep (hrs)", labels=[">8","≤8"]), Theme(point_size=2mm, key_swatch_color="slategrey", point_shapes=[Shape.utriangle, Shape.dtriangle]) ) ``` -------------------------------- ### Apply Theme Temporarily with with_theme Do-Block in Gadfly Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/themes.md This example demonstrates using `with_theme` with a do-block to temporarily apply a theme. The specified theme is active only within the scope of the do-block, ensuring that the theme is automatically reverted to its previous state once the block exits, providing a clean way to apply transient styling. ```Julia Gadfly.with_theme(latex_fonts) do gasoline = dataset("Ecdat", "Gasoline") plot(gasoline, x=:Year, y=:LGasPCar, color=:Country, Geom.point, Geom.line) end ``` -------------------------------- ### Annotating Plots with Custom Shapes (Gadfly) Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/guides.md This snippet demonstrates how to add custom graphical annotations, such as circles, to a plot using `Guide.annotation` in conjunction with `Compose.jl` for drawing shapes. It allows for precise placement and styling of arbitrary graphics on the plot. ```Julia using Gadfly, Compose set_default_plot_size(14cm, 8cm) plot(sin, 0, 2pi, Guide.annotation(compose(context(), Shape.circle([pi/2, 3*pi/2], [1.0, -1.0], [2mm]), fill(nothing), stroke("orange")))) ``` -------------------------------- ### Visualizing Data Distributions with Geom.boxplot in Gadfly.jl Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/gallery/geometries.md Shows how to generate box plots using `Geom.boxplot` to display the distribution of numerical data across different categories. The examples demonstrate basic box plots and more complex ones with additional styling and grouping by color. ```Julia using Compose, Gadfly, RDatasets set_default_plot_size(21cm, 8cm) singers, salaries = dataset("lattice", "singer"), dataset("car","Salaries") salaries.Salary /= 1000.0 salaries.Discipline = ["Discipline $(x)" for x in salaries.Discipline] p1 = plot(singers, x=:VoicePart, y=:Height, Geom.boxplot, Theme(default_color="MidnightBlue")) p2 = plot(salaries, x=:Discipline, y=:Salary, color=:Rank, Scale.x_discrete(levels=["Discipline A", "Discipline B"]), Geom.boxplot, Theme(boxplot_spacing=0.1cx), Guide.colorkey(title="", pos=[0.78w,-0.4h]) ) hstack(p1, p2) ``` -------------------------------- ### Prepare directory for Julia system image compilation Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/index.md Commands to create a dedicated directory and navigate into it, preparing the environment for building a custom Julia system image with precompiled packages. ```bash mkdir $HOME/JuliaGadflySysImage cd $HOME/JuliaGadflySysImage ``` -------------------------------- ### Initialize Gadfly and Load Iris Dataset Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/tutorial.md This code snippet demonstrates how to import the Gadfly and RDatasets packages in Julia, load the Fisher's iris dataset, and set a default plot size for subsequent visualizations. It prepares the environment for plotting. ```Julia using Gadfly, RDatasets iris = dataset("datasets", "iris") set_default_plot_size(14cm, 8cm) # hide nothing # hide ``` -------------------------------- ### Render Plot to SVG File using Function Chaining Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/backends.md A more concise way to render a plot 'p' to an SVG file is by utilizing Julia's function chaining syntax. This example saves the plot 'p' as 'foo.svg' with specified dimensions (6 inches by 4 inches) using the pipe operator. ```julia p |> SVG("foo.svg", 6inch, 4inch) ``` -------------------------------- ### Apply Built-in Named Theme in Gadfly Source: https://github.com/giovineitalia/gadfly.jl/blob/master/docs/src/man/themes.md This example shows how to apply one of Gadfly's built-in named themes, specifically the `:dark` theme. Using `Gadfly.with_theme(:dark)` quickly changes the plot's appearance to a predefined dark mode style, demonstrating the convenience of pre-configured themes. ```Julia Gadfly.with_theme(:dark) do plot(dataset("datasets", "iris"), x=:SepalLength, y=:SepalWidth, color=:Species) end ```