### Initializing StatsPlots and GR Backend in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates the initial setup for using StatsPlots.jl. It covers installing the package if not already present, importing it into the current session (which re-exports Plots.jl), and configuring the GR plotting backend with a specific plot size. ```Julia #]add StatsPlots # install the package if it isn't installed using StatsPlots # no need for `using Plots` as that is reexported here gr(size=(400,300)) ``` -------------------------------- ### Integrating @df Macro with Query.jl Pipelines in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example demonstrates the seamless integration of the `@df` macro with Query.jl pipelines. It allows plotting data directly at the end of a query chain without needing to explicitly collect the query's outcome first, streamlining data manipulation and visualization workflows. ```Julia using Query, StatsPlots df |> @filter(_.a > 5) |> @map({_.b, d = _.c-10}) |> @df scatter(:b, :d) ``` -------------------------------- ### Creating Asymmetric Violin and Dot Plots in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example illustrates how to create asymmetric violin and dot plots using the `side` keyword (`:right` or `:left`) to compare two related datasets. It shows how to plot distributions from `singers` and `singers_moscow` side-by-side for visual comparison, also mentioning the `mode` option for dot plot behavior. ```julia singers_moscow = deepcopy(singers) singers_moscow[:Height] = singers_moscow[:Height] .+ 5 @df singers violin(string.(:VoicePart), :Height, side=:right, linewidth=0, label="Scala") @df singers_moscow violin!(string.(:VoicePart), :Height, side=:left, linewidth=0, label="Moscow") @df singers dotplot!(string.(:VoicePart), :Height, side=:right, marker=(:black,stroke(0)), label="") @df singers_moscow dotplot!(string.(:VoicePart), :Height, side=:left, marker=(:black,stroke(0)), label="") ``` -------------------------------- ### Grouping by Multiple Columns with @df Macro in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example extends the grouping functionality by demonstrating how to group data by more than one column. By providing a tuple of symbols to the `group` argument, users can create plots that segment data based on multiple categorical variables, enhancing comparative analysis. ```Julia @df school density(:MAch, group = (:Sx, :Sector), legend = :topleft) ``` -------------------------------- ### Generating Compact Corner Plot from a Matrix in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example shows how to generate a compact version of the corner plot from matrix `M` by setting `compact=true`. This option typically removes redundant plots (e.g., upper triangle of scatter plots) for a more concise visualization. ```julia cornerplot(M, compact=true) ``` -------------------------------- ### Referencing Columns by Variable with @df and cols() in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example shows how the `cols` utility function can be used with a variable that holds a column symbol. This allows for dynamic selection of columns, making plot commands more flexible and reusable. ```Julia s = :b @df df plot(:a, cols(s)) ``` -------------------------------- ### Generating Marginal Kernel Density Estimate in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example shows how to generate a marginal kernel density estimate plot for two arrays, `x` and `y`, using the `marginalkde` function. It visualizes the joint density and individual marginal densities of the data. Optional parameters like `levels` and `clip` can be used to customize the plot's appearance and bounds. ```julia x = randn(1024) y = randn(1024) marginalkde(x, x+y) ``` -------------------------------- ### Plotting DataFrame Columns with @df Macro in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example illustrates how to use the `@df` macro to plot columns from table-like data structures such as DataFrames and IndexedTables. Columns can be referenced directly by their symbols and manipulated within the plot call, enabling flexible data visualization. ```Julia using DataFrames, IndexedTables df = DataFrame(a = 1:10, b = 10 .* rand(10), c = 10 .* rand(10)) @df df plot(:a, [:b :c], colour = [:red :blue]) @df df scatter(:a, :b, markersize = 4 .* log.(:c .+ 0.1)) t = table(1:10, rand(10), names = [:a, :b]) # IndexedTable @df t scatter(2 .* :b) ``` -------------------------------- ### Creating a Heatmap with Row and Column Dendrograms in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This comprehensive example demonstrates how to create a heatmap with dendrograms on both the top (columns) and right (rows) sides. It uses `Distances.jl` for distance calculation, `Clustering.jl` for hierarchical clustering, and `StatsPlots.jl` for plotting. The data is reordered based on clustering results, and a `grid` layout is used to arrange the heatmap and two dendrograms. ```Julia using Distances using Clustering using StatsBase using StatsPlots pd=rand(Float64,16,7) dist_col=pairwise(CorrDist(),pd,dims=2) hc_col=hclust(dist_col, branchorder=:optimal) dist_row=pairwise(CorrDist(),pd,dims=1) hc_row=hclust(dist_row, branchorder=:optimal) pdz=similar(pd) for row in hc_row.order pdz[row,hc_col.order]=zscore(pd[row,hc_col.order]) end nrows=length(hc_row.order) rowlabels=(1:16)[hc_row.order] ncols=length(hc_col.order) collabels=(1:7)[hc_col.order] l = grid(2,2,heights=[0.2,0.8,0.2,0.8],widths=[0.8,0.2,0.8,0.2]) plot( layout = l, plot(hc_col,xticks=false), plot(ticks=nothing,border=:none), plot( pdz[hc_row.order,hc_col.order], st=:heatmap, #yticks=(1:nrows,rowlabels), yticks=(1:nrows,rowlabels), xticks=(1:ncols,collabels), xrotation=90, colorbar=false ), plot(hc_row,yticks=false,xrotation=90,orientation=:horizontal,xlim=(0,1)) ) ``` -------------------------------- ### Creating Correlation Plot from DataFrame Columns by Name in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example demonstrates how to generate a correlation plot (`corrplot`) from specific columns of a DataFrame using their names. The `@df` macro simplifies accessing DataFrame columns, and `grid = false` disables the grid lines on the plot. ```julia @df iris corrplot([:SepalLength :SepalWidth :PetalLength :PetalWidth], grid = false) ``` -------------------------------- ### Custom Grouped Bar Plot with `group` Syntax in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This example demonstrates using the `group` keyword with `groupedbar` to create a custom grouped bar plot. It defines categories and names, then plots scores, labeling axes and adding a title, with a specific bar width and no line width. ```Julia ctg = repeat(["Category 1", "Category 2"], inner = 5) nam = repeat("G" .* string.(1:5), outer = 2) groupedbar(nam, rand(5, 2), group = ctg, xlabel = "Groups", ylabel = "Scores", title = "Scores by group and category", bar_width = 0.67, lw = 0, framestyle = :box) ``` -------------------------------- ### Creating an Interactive Data Viewer with StatsPlots and Interact.jl in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates how to create an interactive GUI for visualizing tables using StatsPlots, Interact.jl, and Blink.jl. This application can be deployed in various environments like Jupyter notebooks or a browser, providing a dynamic way to explore datasets. ```Julia import RDatasets iris = RDatasets.dataset("datasets", "iris") using StatsPlots, Interact using Blink w = Window() body!(w, dataviewer(iris)) ``` -------------------------------- ### Creating Quantile-Quantile Plots in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates various `qqplot` and `qqnorm` functionalities. It compares two random samples (`x` from Normal, `y` from Cauchy), compares a sample to a fitted Cauchy distribution, and compares a sample to a Normal distribution using `qqnorm`, showing different `qqline` options. ```Julia x = rand(Normal(), 100) y = rand(Cauchy(), 100) plot( qqplot(x, y, qqline = :fit), # qqplot of two samples, show a fitted regression line qqplot(Cauchy, y), # compare with a Cauchy distribution fitted to y; pass an instance (e.g. Normal(0,1)) to compare with a specific distribution qqnorm(x, qqline = :R) # the :R default line passes through the 1st and 3rd quartiles of the distribution ) ``` -------------------------------- ### Generating Equal-Area Histograms in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates the creation of an equal-area histogram using `ea_histogram`. This alternative histogram implementation ensures that every 'box' contains the same number of sample points and has the same area, making it effective for highlighting spikes in data distribution. ```julia a = [randn(100); randn(100) .+ 3; randn(100) ./ 2 .+ 3] ea_histogram(a, bins = :scott, fillalpha = 0.4) ``` -------------------------------- ### Generating a Basic Dendrogram in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates how to create a basic dendrogram using the `Clustering` package. It generates a random distance matrix, performs hierarchical clustering with single linkage, and then plots the resulting dendrogram. ```Julia using Clustering D = rand(10, 10) D += D' hc = hclust(D, linkage=:single) plot(hc) ``` -------------------------------- ### Creating Correlation Plot from a Matrix in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This code demonstrates how to generate a correlation plot directly from a numerical matrix `M`. It initializes a random matrix, introduces some correlations between its columns, and then plots the correlations, providing labels for each variable. ```julia M = randn(1000,4) M[:,2] .+= 0.8sqrt.(abs.(M[:,1])) .- 0.5M[:,3] .+ 5 M[:,3] .-= 0.7M[:,1].^2 .+ 2 corrplot(M, label = ["x$i" for i=1:4]) ``` -------------------------------- ### Visualizing Hierarchical Clustering with Optimal Ordering in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates how to perform hierarchical clustering with optimal branch ordering and visualize the resulting dendrogram alongside a reordered heatmap. It uses `hclust` for clustering and `plot` and `heatmap` from `Plots.jl` (or `StatsPlots.jl`) for visualization. The `layout` function arranges the dendrogram above the heatmap. ```Julia hcl2 = hclust(dm, linkage=:average, branchorder=:optimal) plot( plot(hcl2, xticks=false), heatmap(mat[:, hcl2.order], colorbar=false, xticks=(1:n, ["$i" for i in hcl2.order])), layout=grid(2,1, heights=[0.2,0.8]) ) ``` -------------------------------- ### Dendrogram and Heatmap with Optimal Branch Ordering in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet illustrates the use of `branchorder=:optimal` in `hclust` to minimize leaf distance. It creates a banded matrix, randomizes its order, computes pairwise Euclidean distances, and then plots a dendrogram with a corresponding heatmap, showing the effect of optimal ordering on the visual representation. ```Julia using Clustering using Distances using StatsPlots using Random n = 40 mat = zeros(Int, n, n) # create banded matrix for i in 1:n last = minimum([i+Int(floor(n/5)), n]) for j in i:last mat[i,j] = 1 end end # randomize order mat = mat[:, randperm(n)] dm = pairwise(Euclidean(), mat, dims=2) # normal ordering hcl1 = hclust(dm, linkage=:average) plot( plot(hcl1, xticks=false), heatmap(mat[:, hcl1.order], colorbar=false, xticks=(1:n, ["$i" for i in hcl1.order])), layout=grid(2,1, heights=[0.2,0.8]) ) ``` -------------------------------- ### Visualizing a Gamma Distribution with Scatter and Bar Plots in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This code plots a `Gamma` distribution. It first creates a scatter plot of the distribution and then overlays a bar plot representing its cumulative distribution function (CDF) with 30% transparency. ```Julia dist = Gamma(2) scatter(dist, leg=false) bar!(dist, func=cdf, alpha=0.3) ``` -------------------------------- ### Plotting a Normal Distribution in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates plotting a `Normal` distribution from the `Distributions` package. It visualizes a normal distribution with a mean of 3 and standard deviation of 5, filling the area under the curve with 50% opacity orange. ```Julia using Distributions plot(Normal(3,5), fill=(0, .5,:orange)) ``` -------------------------------- ### Combining Violin, Box, and Dot Plots with DataFrames in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates how to combine violin, box, and dot plots on a single graph using data from a DataFrame. It visualizes the `Height` distribution across different `VoicePart` categories from the `singers` dataset, layering `violin`, `boxplot!`, and `dotplot!` functions. ```julia import RDatasets singers = RDatasets.dataset("lattice", "singer") @df singers violin(string.(:VoicePart), :Height, linewidth=0) @df singers boxplot!(string.(:VoicePart), :Height, fillalpha=0.75, linewidth=2) @df singers dotplot!(string.(:VoicePart), :Height, marker=(:black, stroke(0))) ``` -------------------------------- ### Creating Stacked Grouped Histograms in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet uses the Iris dataset to create a stacked grouped histogram of `SepalLength` grouped by `Species`. The `bar_position = :stack` option stacks the histograms for different species on top of each other. ```Julia @df iris groupedhist(:SepalLength, group = :Species, bar_position = :stack) ``` -------------------------------- ### Creating Marginal Histogram with DataFrames in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates how to generate a marginal histogram using the `marginalhist` function with DataFrames. It visualizes the distribution of two specified columns, `:PetalLength` and `:PetalWidth`, from the `iris` dataset, showing their individual and joint distributions. ```julia using RDatasets iris = dataset("datasets","iris") @df iris marginalhist(:PetalLength, :PetalWidth) ``` -------------------------------- ### Plotting Multi-Dimensional Scaling (MDS) with StatsPlots.jl Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet illustrates how to perform Multi-Dimensional Scaling (MDS) using `MultivariateStats.jl` and visualize the results with `StatsPlots.jl`. It loads the `iris` dataset, applies MDS to reduce dimensionality to 2, and then plots the results, grouping points by species. This helps in visualizing high-dimensional data in a lower-dimensional space. ```Julia using MultivariateStats, RDatasets, StatsPlots iris = dataset("datasets", "iris") X = convert(Matrix, iris[:, 1:4]) M = fit(MDS, X'; maxoutdim=2) plot(M, group=iris.Species) ``` -------------------------------- ### Grouping Data with @df Macro in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet illustrates how to use the `@df` macro in conjunction with Plots.jl's grouping machinery. It shows how to create a density plot, grouping the data based on a specified column, which is useful for comparing distributions across different categories. ```Julia using RDatasets school = RDatasets.dataset("mlmRev","Hsb82") @df school density(:MAch, group = :Sx) ``` -------------------------------- ### Visualizing High-Dimensional Data with AndrewsPlot in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates how to create an Andrews Plot using the `RDatasets` package to load the Iris dataset. It visualizes each row of the `iris` DataFrame as a line, with colors grouped by the `Species` column and columns 1-4 used for the plot. The legend is placed at the top-left. ```Julia using RDatasets iris = dataset("datasets", "iris") @df iris andrewsplot(:Species, cols(1:4), legend = :topleft) ``` -------------------------------- ### Creating Dodged Grouped Histograms in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet uses the `RDatasets` package to load the Iris dataset and creates a dodged grouped histogram of `SepalLength` grouped by `Species`. The `bar_position = :dodge` option places the histograms for different species side-by-side. ```Julia using RDatasets iris = dataset("datasets", "iris") @df iris groupedhist(:SepalLength, group = :Species, bar_position = :dodge) ``` -------------------------------- ### Plotting Covariance Ellipses with StatsPlots.jl Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This code demonstrates how to plot 2D covariance ellipses using the `covellipse` and `covellipse!` functions from `StatsPlots.jl`. The first call plots an ellipse centered at `[0,2]` with a specified covariance matrix. The second call adds another ellipse to the same plot, centered at `[1,0]`, showing its axes. ```Julia covellipse([0,2], [2 1; 1 4], n_std=2, aspect_ratio=1, label="cov1") covellipse!([1,0], [1 -0.5; -0.5 3], showaxes=true, label="cov2") ``` -------------------------------- ### Plotting Error Distributions with ErrorLine in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This code generates synthetic data and then uses `errorline` and `errorline!` to plot error distributions with different styles: `:ribbon`, `:stick`, and `:plume`. `errorline` creates a new plot, while `errorline!` adds to the current plot, allowing multiple error lines on one graph. ```Julia x = 1:10 y = fill(NaN, 10, 100, 3) for i = axes(y,3) y[:,:,i] = collect(1:2:20) .+ rand(10,100).*5 .* collect(1:2:20) .+ rand()*100 end errorline(1:10, y[:,:,1], errorstyle=:ribbon, label="Ribbon") errorline!(1:10, y[:,:,2], errorstyle=:stick, label="Stick", secondarycolor=:matched) errorline!(1:10, y[:,:,3], errorstyle=:plume, label="Plume") ``` -------------------------------- ### Generating Corner Plot from a Matrix in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet creates a corner plot (also known as a scatterplot matrix) from the previously defined matrix `M`. A corner plot displays all pairwise scatter plots of variables along with their marginal distributions, providing a comprehensive view of relationships. ```julia cornerplot(M) ``` -------------------------------- ### Creating Stacked Grouped Bar Plots in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet generates a stacked grouped bar plot from random data. The `bar_position = :stack` option ensures that bars for different groups within the same category are stacked on top of each other. ```Julia groupedbar(rand(10,3), bar_position = :stack, bar_width=0.7) ``` -------------------------------- ### Creating Marginal Scatter Plot with DataFrames in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet illustrates how to create a marginal scatter plot using `marginalscatter` with DataFrames. It plots the relationship between `:PetalLength` and `:PetalWidth` from the `iris` dataset, augmented with marginal distributions for each variable. ```julia using RDatasets iris = dataset("datasets","iris") @df iris marginalscatter(:PetalLength, :PetalWidth) ``` -------------------------------- ### Creating Correlation Plot from DataFrame Columns by Index in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet shows an alternative way to create a correlation plot from a DataFrame by selecting columns using their numerical indices. The `cols(1:4)` function selects the first four columns of the `iris` DataFrame for the `corrplot`. ```julia @df iris corrplot(cols(1:4), grid = false) ``` -------------------------------- ### Creating Dodged Grouped Bar Plots in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet generates a dodged grouped bar plot from random data. The `bar_position = :dodge` option (which is the default) places bars for different groups side-by-side within each category. ```Julia groupedbar(rand(10,3), bar_position = :dodge, bar_width=0.7) ``` -------------------------------- ### Setting Plot Size for GR Backend in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet configures the default plot size for the GR backend, which is commonly used with Plots.jl. It sets the plot dimensions to 600 pixels wide by 500 pixels high, affecting subsequent plots. ```julia gr(size = (600, 500)) ``` -------------------------------- ### Referencing Column Ranges with @df and cols() in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet demonstrates using the `cols` utility function within the `@df` macro to refer to a range of columns by their index. This provides a convenient way to select multiple columns for plotting without listing each symbol individually. ```Julia @df df plot(:a, cols(2:3), colour = [:red :blue]) ``` -------------------------------- ### Escaping Ambiguous Symbols in @df Macro in Julia Source: https://github.com/juliaplots/statsplots.jl/blob/master/README.md This snippet addresses potential ambiguities when using the `@df` macro. It shows how to use the `^()` syntax to escape symbols that do not refer to `DataFrame` columns, ensuring they are interpreted correctly as literal values rather than column names. ```Julia df[:red] = rand(10) @df df plot(:a, [:b :c], colour = ^([:red :blue])) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.