StatsPlots.jl

repository·master·Indexed 19 days ago

https://github.com/juliaplots/statsplots.jl

A statistical plotting extension for Plots.jl providing specialized recipes for DataFrames and Distributions. It includes the @df macro for table-based plotting and supports a wide range of statistical visualizations, including violin plots, corner plots, marginal distributions, QQ plots, grouped bar charts, and dendrograms.

Tokens
3.3K
Snippets
16
Records
16
Agent score
16%

What's inside StatsPlots.jl

  1. Visualize a table interactively with dataviewer

    master

    You can create an interactive GUI to explore and plot tables using the dataviewer function from the Interact package. This is useful in Jupyter notebooks, Juno, or Blink windows.

    import RDatasets
    iris = RDatasets.dataset("datasets", "iris")
    using StatsPlots, Interact
    using Blink
    
    w = Window()
    body!(w, dataviewer(iris))
  2. Use the @df macro for table-based plotting

    master

    The @df macro allows you to pass columns of a table (like DataFrames, IndexedTables, or DataStreams) as symbols. This enables plotting directly from data structures without manually extracting arrays.

    Key Features:

    • Column Selection: Use symbols (e.g., :a) or the cols() utility to refer to columns.
    • Range Selection: cols(2:3) selects a range of columns.
    • Variable Symbols: Pass a symbol stored in a variable to cols().
    • Escaping Ambiguity: If a symbol is not a column name but is used in a context that might be confused with one, escape it using ^().
    • Query.jl Integration: You can append @df to the end of a Query.jl pipeline.
    • Grouping: Use the group keyword with a single symbol, a tuple of symbols, or the curly bracket syntax {Name = :col} for custom legend labels.
    using DataFrames, IndexedTables, StatsPlots
    
    df = DataFrame(a = 1:10, b = 10 .* rand(10), c = 10 .* rand(10))
    
    # Basic plotting with symbols
    @df df plot(:a, [:b :c], colour = [:red :blue])
    
    # Using cols() for ranges or variables
    @df df plot(:a, cols(2:3), colour = [:red :blue])
    s = :b
    @df df plot(:a, cols(s))
    
    # Escaping non-column symbols
    df[:red] = rand(10)
    @df df plot(:a, [:b :c], colour = ^([:red :blue]))
    
    # Grouping with custom legend names
    @df school density(:MAch, group = {Sex = :Sx, :Sector})
  3. Install and initialize StatsPlots

    master

    To use StatsPlots, add it via the Julia package manager and load it using using StatsPlots. Note that StatsPlots re-exports Plots.jl, so you do not need to call using Plots separately. It is designed as a drop-in replacement for Plots.jl with added statistical recipes for DataFrames and Distributions.

    #] add StatsPlots
    using StatsPlots
    gr(size=(400,300))
  4. Plot dendrograms

    master

    Dendrograms can be plotted directly from hierarchical clustering results (e.g., from Clustering.jl).

    To improve the visual layout of a heatmap paired with a dendrogram, use the branchorder=:optimal option in the hclust() function. This minimizes the distance between neighboring leaves, making the heatmap structure more apparent.

    using Clustering
    D = rand(10, 10)
    D += D'
    hc = hclust(D, linkage=:single)
    plot(hc)
  5. Generate correlation plots with corrplot and cornerplot

    master

    These functions visualize correlations among multiple variables.

    • corrplot: Shows correlation via scatter plots where marker color indicates the degree of correlation (default: blue for positive, yellow for neutral, red for negative). In 2D histograms, color indicates frequency.
    • cornerplot: A variation of the correlation plot.

    Both functions accept DataFrames (via @df) or raw matrices.

    # From a DataFrame
    @df iris corrplot([:SepalLength :SepalWidth :PetalLength :PetalWidth], grid = false)
    
    # From a Matrix
    M = randn(1000, 4)
    corrplot(M)
    cornerplot(M, compact=true)
  6. Plot covariance ellipses

    master

    The covellipse function plots a 2×2 covariance matrix $\Sigma$ as an ellipse, representing a contour line of a Gaussian density function.

    Key options:

    • n_std: Number of standard deviations for the contour.
    • aspect_ratio: Adjusts the aspect ratio of the ellipse.
    • showaxes: Boolean to show or hide axes.
    • label: String label for the ellipse.
    # Plotting a single ellipse
    covellipse([0,2], [2 1; 1 4], n_std=2, aspect_ratio=1, label="cov1")
    
    # Plotting with axes
    covellipse!([1,0], [1 -0.5; -0.5 3], showaxes=true, label="cov2")
  7. Use marginalkde for kernel density estimation

    master

    The marginalkde(x, y) function plots the joint kernel density estimation of two variables.

    Arguments:

    • levels=N: Sets the number of contour levels (default is 10). Levels are evenly spaced in cumulative probability mass.
    • clip=((-xl, xh), (-yl, yh)): Adjusts plot bounds. Default is ((-3, 3), (-3, 3)), where values are multiples of the [0.16-0.5] and [0.5, 0.84] percentiles of the underlying 1D distributions.
    x = randn(1024)
    y = randn(1024)
    marginalkde(x, x+y)
  8. Visualize high-dimensional data with AndrewsPlot

    master

    An andrewsplot depicts each row of an array or table as a line that varies with the values in the columns, helping to visualize structure in high-dimensional datasets.

    using RDatasets, StatsPlots
    is = dataset("datasets", "iris")
    @df is andrewsplot(:Species, cols(1:4), legend = :topleft)
  9. Plot MDS ordinations

    master

    Multidimensional Scaling (MDS) results from MultivariateStats.jl can be visualized as scatter plots. You can use the group keyword to color points by a categorical variable (e.g., species).

    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)
  10. Create boxplots, dotplots, and violin plots

    master

    These recipes allow for visualizing distributions across categories.

    • violin: Creates violin plots. Use side=:left or side=:right for asymmetric plots.
    • boxplot!: Creates box plots.
    • dotplot!: Creates dot plots.
      • mode=:density (default): Dots are restricted to the kernel density (width of a violin plot).
      • mode=:uniform: Dots spread over the full width of the column.
      • mode=:none: Dots stay along the center line.
    import RDatasets, StatsPlots
    singers = RDatasets.dataset("lattice", "singer")
    
    # Violin plot
    @df singers violin(string.(:VoicePart), :Height, linewidth=0)
    
    # Boxplot
    @df singers boxplot!(string.(:VoicePart), :Height, fillalpha=0.75, linewidth=2)
    
    # Dotplot
    @df singers dotplot!(string.(:VoicePart), :Height, marker=(:black, stroke(0)))
    
    # Asymmetric violin/dot plots
    @df singers violin(string.(:VoicePart), :Height, side=:right, linewidth=0)
  11. Plot error distributions with ErrorLine

    master

    The errorline function visualizes error distributions for line plots using different styles.

    Styles (errorstyle):

    • :ribbon (similar to ggplot2's ribbon)
    • :stick (similar to MATLAB's errorbar)
    • :plume (plume style)
    x = 1:10
    y = fill(NaN, 10, 100, 3)
    # ... (data generation) ...
    
    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")
  12. Create grouped histograms

    master

    Use groupedhist to create histograms that are split by a categorical variable. This is often used with DataFrames via the @df macro. You can control the layout using bar_position.

    Key options:

    • group: The column or vector used for grouping.
    • bar_position: Set to :dodge or :stack to control how the histogram bars for different groups are displayed.
    using RDatasets
    iris = dataset("datasets", "iris")
    
    # Dodged grouped histogram
    @df iris groupedhist(:SepalLength, group = :Species, bar_position = :dodge)
    
    # Stacked grouped histogram
    @df iris groupedhist(:SepalLength, group = :Species, bar_position = :stack)