### Setup for JuliaPlots Examples Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Initializes Plots and Random, sets a random seed, and configures default plotting parameters. ```julia using Plots, Random Random.seed!(100) default(legend = :topleft, markerstrokecolor = :auto, markersize = 6) ``` -------------------------------- ### Simplifying PyPlot backend installation Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Streamlines the process of installing and setting up the PyPlot backend. ```julia simplify PyPlot backend installation ``` -------------------------------- ### Example Usage of Type Recipe for MyWrapper Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md This example demonstrates plotting a `MyWrapper` object after its type recipe has been defined. It assumes `MyWrapper` and its recipe are already set up. ```julia mw = MyWrapper(cumsum(rand(10))) plot(mw) ``` -------------------------------- ### Initialize StatsPlots Source: https://github.com/juliaplots/plots.jl/blob/v2/StatsPlots/README.md Install and load the StatsPlots package. `gr()` sets the default backend and 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)) ``` -------------------------------- ### Setup JuliaPlots Ecosystem Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/ecosystem.md Initializes the Plots.jl ecosystem with necessary packages and resets defaults. This setup is common for examples using StatsPlots and other plotting functionalities. ```julia using StatsPlots, Plots, RDatasets, Distributions; gr() PlotsBase.reset_defaults() iris = dataset("datasets", "iris") singers = dataset("lattice","singer") dist = Gamma(2) a = [randn(100); randn(100) .+ 3; randn(100) ./ 2 .+ 3] ``` -------------------------------- ### Usage Example for Custom Recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/recipes.md Shows how to call the custom plot recipe with different arguments and keyword options. ```julia mt = MyType() plot( plot(mt), plot(mt, 100, linecolor = :red), plot(mt, marker = (:star,20), add_marker = false), plot(mt, add_marker = true) ) ``` -------------------------------- ### User Recipe Syntax Example Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Defines the basic signature for a user-defined recipe using the @recipe macro. ```julia @recipe function f(custom_arg_1::T, custom_arg_2::S, ...; ...) ``` -------------------------------- ### Setup GraphRecipes and Plots Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/GraphRecipes/introduction.md Initializes the GraphRecipes and Plots packages and resets defaults. This is typically run at the beginning of a session or script. ```julia using Plots, GraphRecipes; gr() PlotsBase.reset_defaults() ``` -------------------------------- ### Type Recipe Syntax Example Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Defines the signature for a type recipe, specifying how to plot a specific type. ```julia @recipe function f(::Type{T}, val::T) where T ``` -------------------------------- ### Example: Plotting a Histogram Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/internals.md This example shows how to plot a histogram using the Plots package in Julia. Ensure the Plots package is imported before running. ```julia using Plots plot(histogram(randn(1000))) ``` -------------------------------- ### Install GraphRecipes Source: https://github.com/juliaplots/plots.jl/blob/v2/GraphRecipes/README.md Use the Julia package manager to add GraphRecipes to your project. ```julia ] add GraphRecipes ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Set up git hooks to automatically run code quality checks before each commit. This is recommended for maintaining code consistency. ```bash pre-commit install ``` -------------------------------- ### Setup Plots.jl with GR backend Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/index.md Initializes the Plots package and sets the GR backend for plotting. Resets default plot attributes. ```julia using Plots; gr() PlotsBase.reset_defaults() ``` -------------------------------- ### Install GraphRecipes Package Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/GraphRecipes/introduction.md Installs the GraphRecipes package using the Julia package manager. ```julia ] add GraphRecipes ``` -------------------------------- ### Example Usage of Type Recipe for MyTime Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md This example plots a vector of `MyTime` objects, showcasing the automatic application of the custom type recipe for correct tick labeling. It assumes the `MyTime` type and its recipe are defined. ```julia times = MyTime.(0:23, rand(0:59, 24)) vals = log.(1:24) plot(times, vals) ``` -------------------------------- ### Install PlotThemes.jl Source: https://github.com/juliaplots/plots.jl/blob/v2/PlotThemes/README.md Use this command to add the PlotThemes.jl package to your Julia environment. ```julia Pkg.add("PlotThemes") ``` -------------------------------- ### Series Recipe Syntax Example Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Defines the signature for a series recipe, used for plotting x, y, and optionally z data. ```julia @recipe function f(::Type{Val{:myseriesrecipename}}, x, y, z; ...) ``` -------------------------------- ### Displaying Pie Chart Plot Recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Example of displaying a pie chart using the `plotpie` plot recipe with a layout. ```julia plotpie(rand(4, 2), layout = (1, 2)) ``` -------------------------------- ### Example of Composing Type and Plot Recipes Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md This example shows how type recipes and plot recipes can be composed seamlessly. It uses the `yscaleplot` plot recipe with custom wrapped types (`MyWrapper`, `MyOtherWrapper`). ```julia plot(MyWrapper(times), MyOtherWrapper((1:24).^2)) ``` ```julia yscaleplot(MyWrapper(times), MyOtherWrapper((1:24).^2)) ``` -------------------------------- ### Displaying Pie Chart Series Recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Example of displaying a pie chart using the `seriespie` recipe. This works with basic data, custom wrapper types, and layouts. ```julia seriespie(rand(4)) ``` ```julia seriespie(MyWrapper(rand(4))) ``` ```julia seriespie(rand(4, 2), layout = 2) ``` -------------------------------- ### Setup plot and subplots Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/internals.md After all recipes have been applied, _plot_setup and _subplot_setup are called to finalize the plot and subplot configurations based on the processed plot attributes and keyword arguments. ```julia _plot_setup(plt, plotattributes, kw_list) _subplot_setup(plt, plotattributes, kw_list) ``` -------------------------------- ### Define Example Data Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/pipeline.md Generates sample data for plotting, including a range for the x-axis and a matrix for y-values. ```julia n = 100 x, y = range(0, 1, length = n), randn(n, 3) ``` -------------------------------- ### Example Usage of Plot Recipe yscaleplot Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md This example calls the `yscaleplot` plot recipe with a simple vector, demonstrating its ability to create plots with different y-scales. The `@shorthands` macro must be applied beforehand. ```julia @shorthands yscaleplot yscaleplot((1:10).^2) ``` -------------------------------- ### Select Gaston Backend Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/backends.md Select the Gaston backend for Plots.jl. This is a setup step. ```julia gaston(); backendplot() #hide ``` -------------------------------- ### Plotting with a Custom User Pie Recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Example of how to use the custom `userpie` recipe to generate a pie chart with specified labels and data. ```julia userpie('A':'D', rand(4)) ``` -------------------------------- ### Initialize Animation and Save Frames Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/animations.md This snippet shows the basic setup for creating an animation by initializing an Animation object, saving frames using `frame(anim)`, and finally converting it to a GIF using `gif(anim, filename, fps=15)`. It's a more verbose method compared to the convenience macros. ```julia using Plots; gr() PlotsBase.reset_defaults() ``` ```julia using Plots @userplot CirclePlot @recipe function f(cp::CirclePlot) x, y, i = cp.args n = length(x) inds = circshift(1:n, 1 - i) linewidth --> range(0, 10, length = n) seriesalpha --> range(0, 1, length = n) aspect_ratio --> 1 label --> false x[inds], y[inds] end n = 150 t = range(0, 2π, length = n) x = sin.(t) y = cos.(t) anim = @animate for i ∈ 1:n circleplot(x, y, i) end gif(anim, "anim_fps15.gif", fps = 15) ``` -------------------------------- ### Switch to PythonPlot Backend Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/gallery/pythonplot/index.md Use this command to switch the plotting backend to PythonPlot. Ensure you have the necessary Python packages installed. ```julia using Plots pythonplot() ``` -------------------------------- ### Plot Recipe Syntax Example Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Defines the signature for a plot recipe, identified by a specific symbol name. ```julia @recipe function f(::Type{Val{:myplotrecipename}}, plt::AbstractPlot; ...) ``` -------------------------------- ### Format Code with Runic Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Run this command to format your code changes in-place using the Runic tool. Ensure Runic is installed and configured. ```bash $ julia -e 'using Runic; exit(Runic.main(ARGS))' -- --inplace . ``` -------------------------------- ### Create a 4x1 grid layout Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/layouts.md Pass a tuple to `layout` to specify the grid dimensions. This example creates a 4x1 grid for 4 series. ```julia plot(rand(100, 4); layout = (4, 1)) ``` -------------------------------- ### Troubleshooting: MethodError start(::Void) Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/recipes.md This error commonly occurs when a series type expects data for x, y, or z but receives `nothing` (Void). Verify that all required data values are provided and are not null. ```text ERROR: MethodError: `start` has no method matching start(::Void) in collect at ./array.jl:260 in collect at ./array.jl:272 in plotly_series at ~/.julia/v0.4/Plots/src/backends/plotly.jl:345 in _series_added at ~/.julia/v0.4/Plots/src/backends/plotlyjs.jl:36 in _apply_series_recipe at ~/.julia/v0.4/Plots/src/plot.jl:224 in _plot! at ~/.julia/v0.4/Plots/src/plot.jl:537 ``` -------------------------------- ### Initialize GR Backend and Plot Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/backends.md Initializes the GR backend for Plots.jl and calls the custom 'backendplot' function. This is a basic example to demonstrate backend usage. ```julia gr(); backendplot() #hide ``` -------------------------------- ### Define a simple recipe for a surface plot Source: https://github.com/juliaplots/plots.jl/blob/v2/RecipesBase/README.md This example demonstrates how to define a basic recipe for a surface plot using the @recipe macro. It defines a function for a custom type `T` that returns a random 100x100 matrix, which is then plotted as a surface. ```julia using Plots; gr() struct T end @recipe f(::T) = rand(100,100) surface(T()) ``` -------------------------------- ### Basic Contour Plot Setup Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/series_types/contour.md Sets up the Plots.jl environment with the PythonPlot backend and defines a function and data for a contour plot. Use this for initial contour plot generation. ```julia using Plots; pythonplot() f(x, y) = (3x + y^2) * abs(sin(x) + cos(y)) x = range(0, 5, length=100) y = range(0, 3, length=50) z = @. f(x', y) contour(x, y, z) ``` -------------------------------- ### Custom Recipe Example with Attribute Operators Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/recipes.md Demonstrates defining a custom type for dispatch and using --> and := operators to set plot attributes. The return value is the data to be plotted. ```julia mutable struct MyType end @recipe function f(::MyType, n::Integer = 10; add_marker = false) linecolor --> :blue seriestype := :path markershape --> (add_marker ? :circle : :none) delete!(plotattributes, :add_marker) rand(n) end ``` -------------------------------- ### Using a custom recipe with Plots.jl Source: https://github.com/juliaplots/plots.jl/blob/v2/RecipesBase/README.md This example demonstrates how to use the custom recipe defined previously with the Plots.jl library. The call to plot implicitly invokes `RecipesBase.apply_recipe` during the Plots processing pipeline. It plots multiple line plots with custom marker and color settings. ```julia # Plots will be the ultimate consumer of our recipe in this example using Plots gr() # This call will implicitly call `RecipesBase.apply_recipe` as part of the Plots # processing pipeline (see the Pipeline section of the Plots documentation). # It will plot 5 line plots (a 5-column matrix is returned from the recipe). # All will have black circles: # - user override for markershape: :c ≡ :circle # - customcolor overridden to :black, and markercolor is forced to be customcolor ``` -------------------------------- ### Create a 2x2 grid layout Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/layouts.md Pass an integer to `layout` to automatically compute a grid size for that many subplots. This example maps 4 series to a 2x2 grid. ```julia plot(rand(100, 4); layout = 4) ``` -------------------------------- ### Call a Custom Series Recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Example of calling a custom series recipe with a custom wrapper type. This may lead to errors if the wrapper type does not implement required methods like `keys` or `eachindex`. ```julia userpie(MyWrapper(rand(4))) ``` -------------------------------- ### Animate with 'every' Flag Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/animations.md This example shows how to use the `every` flag with the `@gif` macro to save a frame only every N iterations. This is useful for reducing the number of frames and file size for animations where high frame density is not required. ```julia @gif for i ∈ 1:n circleplot(x, y, i, line_z = 1:n, cbar = false, framestyle = :zerolines) end every 5 ``` -------------------------------- ### Plotting with Custom Keywords Source: https://github.com/juliaplots/plots.jl/blob/v2/RecipesBase/README.md Example of calling plot with a custom type and keyword arguments. Unsupported keywords may show warnings or be suppressed. ```julia plot(T(), 5; customcolor = :black, shape=:c) ``` -------------------------------- ### Customize GR Surface Plot with Extra Kwargs Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/backends.md Demonstrates how to fine-tune GR backend features, specifically for a surface plot, by using the 'extra_kwargs' mechanism. This example sets the number of interpolation points and display options for the surface. ```julia using Plots; gr() x = range(-3, 3, length=30) surface( x, x, (x, y)->exp(-x^2 - y^2), c=:viridis, legend=:none, nx=50, ny=50, display_option=Plots.GR.OPTION_SHADED_MESH, # <-- series[:extra_kwargs] ) ``` -------------------------------- ### Generate Marginal Histograms Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/recipes.md Example usage of the marginalhist function with sample data. This demonstrates how to call the custom plot recipe with specific styling options like color and number of bins. ```julia using Distributions n = 1000 x = rand(Gamma(2), n) y = -0.5x + randn(n) marginalhist(x, y, fc = :plasma, bins = 40) ``` -------------------------------- ### Plotting Parametric Functions with Different Range Inputs Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/input_data.md Demonstrates three ways to plot parametric functions using a vector of time points, a function with a time vector, or a function with a start and end time. ```julia using Plots tmin = 0 tmax = 4π tvec = range(tmin, tmax, length = 100) plot(sin.(tvec), cos.(tvec)) ``` ```julia plot(sin, cos, tvec) ``` ```julia plot(sin, cos, tmin, tmax) ``` -------------------------------- ### Documenting `:colorbar_entry` Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Adds documentation for the `:colorbar_entry` option, explaining its usage. ```julia document :colorbar_entry ``` -------------------------------- ### Define a custom recipe with attributes Source: https://github.com/juliaplots/plots.jl/blob/v2/RecipesBase/README.md This example shows how to define a more complex recipe for a user-defined type `T`. It uses the @recipe macro to specify plot attributes like `markershape`, `markercolor`, `xrotation`, and `zrotation`. The `-->` operator sets default values if unset, while `:=` forces a specific value. The recipe returns data for subsequent processing. ```julia using RecipesBase # Our user-defined data type struct T end # This is all we define. It uses a familiar signature, but strips it apart # in order to add a custom definition to the internal method `RecipesBase.apply_recipe` @recipe function plot(::T, n = 1; customcolor = :green) markershape --> :auto # if markershape is unset, make it :auto markercolor := customcolor # force markercolor to be customcolor xrotation --> 45 # if xrotation is unset, make it 45 zrotation --> 90 # if zrotation is unset, make it 90 rand(10,n) # return the arguments (input data) for the next recipe end ``` -------------------------------- ### Configure Backend Defaults Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/install.md Sets default plotting parameters for specific backends. For example, `gr()` can configure size and legend visibility, while `unicodeplots()` enables terminal plotting, `pgfplotsx()` prepares for PGFPlotsX, and `plotly()` with `ticks=:native` enhances PlotlyJS saving options. ```julia gr(size = (300, 300), legend = false) # provide optional defaults ``` ```julia unicodeplots() # plot in terminal ``` ```julia pgfplotsx() ``` ```julia plotly(ticks=:native) # plotlyjs for richer saving options ``` ```julia pythonplot() # backends are selected with lowercase names ``` -------------------------------- ### Define type recipes for argument signatures Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/internals.md Plots defines type recipes for common argument signatures like (x, y). This example shows how a two-argument type recipe handles potential replacements of arguments using _apply_type_recipe and falls back to SliceIt if no replacements occur. ```julia @recipe function f(x, y) did_replace = false newx = _apply_type_recipe(plotattributes, x) x === newx || (did_replace = true) newy = _apply_type_recipe(plotattributes, y) y === newy || (did_replace = true) if did_replace newx, newy else SliceIt, x, y, nothing end end ``` -------------------------------- ### Add Plots.jl Package Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/install.md Installs the main Plots package and its default GR backend. Use the second command to install PlotsBase with a specific backend like PythonPlot, avoiding the GR dependency. The third command adds the latest features from the v2 branch. ```julia import Pkg Pkg.add("Plots") # ≡ `PlotsBase` + `GR` backend ``` ```julia Pkg.add("PlotBase", "PythonPlot") # `PlotsBase` + `PythonPlot` backend, which avoids installing the `GR` backend ``` ```julia # if you want the latest features: Pkg.pkg"add Plots#v2" ``` -------------------------------- ### Add Supported Backends for Plots.jl Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/install.md Installs various optional plotting backends for Plots.jl. Note that GR is the default and usually doesn't need explicit installation. UnicodePlots is suitable for terminals, PythonPlot requires Python, PGFPlotsX needs LaTeX, PlotlyJS offers advanced features, and Gaston uses Gnuplot. ```julia Pkg.add("GR") ``` ```julia # You do not need to add this package because it is the default backend and # therefore it is automatically installed with Plots.jl. Note that you might # need to install additional system packages if you are on Linux, see # https://gr-framework.org/julia.html#installation ``` ```julia Pkg.add("UnicodePlots") # simplest terminal based backend (guaranteed to work from a cluster, e.g. without X forwarding) ``` ```julia Pkg.add("PythonPlot") # depends only on PythonPlot package ``` ```julia Pkg.add("PGFPlotsX") # you need to have LaTeX installed on your system ``` ```julia Pkg.add("PlotlyJS") ``` ```julia # Note that you only need to add this if you need Electron windows and # additional output formats, otherwise `plotly()` comes shipped with Plots.jl. # In order to have a good experience with Jupyter, refer to Plotly-specific # Jupyter installation (https://github.com/plotly/plotly.py#installation) ``` ```julia Pkg.add("Gaston") # Gnuplot based backend ``` -------------------------------- ### Adding `portfoliodecomposition` recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Includes the `portfoliodecomposition` recipe, likely for financial analysis visualizations. ```julia add portfoliodecomposition recipe from PlotRecipes ``` -------------------------------- ### Add, Commit, and Push Changes Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Stage your changes, commit them with a descriptive message, and push them to your forked repository. The `-a` flag stages all modified tracked files, and `-m` provides a commit message. ```bash git add src/my_new_file.jl git commit -am "my commit message" git push forked user123-dev ``` -------------------------------- ### Initialize Plots.jl and Select Backend Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/install.md Loads the Plots.jl package (or StatsPlots) for use. The commented-out lines show how to optionally load GraphRecipes. The alternative initialization demonstrates selecting and activating a specific backend like PythonPlot. ```julia using Plots # or StatsPlots # using GraphRecipes # if you wish to use GraphRecipes package too ``` ```julia # or alternatively import PythonPlot # select installed backend (triggered by packages extensions: https://docs.julialang.org/en/v1/manual/code-loading/#man-extensions) using PlotsBase pythonplot() # activate the chosen backend ``` -------------------------------- ### Troubleshooting: Cannot convert Float64 to RecipeData Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/recipes.md This error arises when using the `return` keyword within a recipe, which is unsupported in RecipesBase versions prior to 0.9. Ensure you are using a compatible version or avoid using `return` in recipes. ```text ERROR: MethodError: Cannot `convert` an object of type Float64 to an object of type RecipeData Closest candidates are: convert(::Type{T}, ::T) where T at essentials.jl:171 RecipeData(::Any, ::Any) at ~/.julia/packages/RecipesBase/G4s6f/src/RecipesBase.jl:57 ``` -------------------------------- ### Call User Recipe with Random Integers (Illustrates Genericity Issue) Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Demonstrates calling the custom 'mycount' recipe with a randomly generated array of 500 integers, highlighting a potential issue if genericity is not fully considered. ```julia mycount(rand(1:500, 500)) ``` -------------------------------- ### Initialize Plots with Data in Julia Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/basics.md Demonstrates various ways to initialize a plot object with different data inputs, including empty plots, random data, functions, and DataFrame columns. ```julia plot() # empty Plot object ``` ```julia plot(4) # initialize with 4 empty series ``` ```julia plot(rand(10)) # 1 series... x = 1:10 ``` ```julia plot(rand(10,5)) # 5 series... x = 1:10 ``` ```julia plot(rand(10), rand(10)) # 1 series ``` ```julia plot(rand(10,5), rand(10)) # 5 series... y is the same for all ``` ```julia plot(sin, rand(10)) # y = sin.(x) ``` ```julia plot(rand(10), sin) # same... y = sin.(x) ``` ```julia plot([sin,cos], 0:0.1:π) # 2 series, sin.(x) and cos.(x) ``` ```julia plot([sin,cos], 0, π) # sin and cos on the range [0, π] ``` ```julia plot(1:10, Any[rand(10), sin]) # 2 series: rand(10) and map(sin,x) ``` ```julia @df dataset("Ecdat", "Airline") plot(:Cost) # the :Cost column from a DataFrame... must import StatsPlots ``` -------------------------------- ### Add Plots Ecosystem Extensions Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/install.md Installs additional extensions for the Plots.jl ecosystem, such as StatsPlots for statistical plotting and GraphRecipes for plotting graph structures. ```julia Pkg.add("StatsPlots") ``` ```julia Pkg.add("GraphRecipes") ``` -------------------------------- ### Call User Recipe with Random Strings Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Demonstrates calling the custom 'mycount' recipe with a randomly generated array of 100 strings. ```julia mycount(rand(["A","B","C"],100)) ``` -------------------------------- ### Create a Scatter Plot with Noisy Data Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/tutorial.md Use `seriestype=:scatter` to create a scatter plot. This example plots a noisy sine wave. ```julia x = range(0, 10, length=100) y = sin.(x) y_noisy = @. sin(x) + 0.1*randn() plot(x, y, label="sin(x)") plot!(x, y_noisy, seriestype=:scatter, label="data") ``` -------------------------------- ### Switch to PGFPlotsX Backend Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/gallery/pgfplotsx/index.md Use this command to switch the plotting backend to PGFPlotsX. Ensure Plots is imported first. ```julia using Plots pgfplotsx() ``` -------------------------------- ### Plotting Result with error band Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/syntax.md Example of manually plotting a Result type with an error band. This demonstrates the desired plotting behavior before creating a user recipe. ```julia res = Result(1:10, cumsum(rand(10)), cumsum(rand(10)) / 5) using Plots # plot the error band as invisible line with fillrange plot( res.x, res.y .+ res.ε, xlabel = "x", ylabel = "y", fill = (res.y .- res.ε, :lightgray, 0.5), linecolor = nothing, primary = false, # no legend entry ) # add the data to the plots plot!(res.x, res.y, marker = :diamond) ``` -------------------------------- ### Implementing arrowstyle for GR backend Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Adds support for `arrowstyle` customization in the GR backend. ```julia implement arrowstyle for GR ``` -------------------------------- ### Set Default Backend via Environment Variable Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/install.md Overrides the default plotting backend by setting the `PLOTSBASE_DEFAULT_BACKEND` environment variable in the `~/.julia/config/startup.jl` file. This example sets UnicodePlots as the default. ```julia ENV["PLOTSBASE_DEFAULT_BACKEND"] = "UnicodePlots" ``` -------------------------------- ### Animate Lorenz Attractor Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/index.md Defines and animates the Lorenz attractor using a mutable struct and the @gif macro. Requires a 3D plot setup and pushes new points in a loop. ```julia using Plots # define the Lorenz attractor Base.@kwdef mutable struct Lorenz dt::Float64 = 0.02 σ::Float64 = 10 ρ::Float64 = 28 β::Float64 = 8/3 x::Float64 = 1 y::Float64 = 1 z::Float64 = 1 end function step!(l::Lorenz) dx = l.σ * (l.y - l.x) dy = l.x * (l.ρ - l.z) - l.y dz = l.x * l.y - l.β * l.z l.x += l.dt * dx l.y += l.dt * dy l.z += l.dt * dz end attractor = Lorenz() # initialize a 3D plot with 1 empty series plt = plot3d( 1, xlim = (-30, 30), ylim = (-30, 30), zlim = (0, 60), title = "Lorenz Attractor", legend = false, marker = 2, ) # build an animated gif by pushing new points to the plot, saving every 10th frame @gif for i=1:1500 step!(attractor) push!(plt, attractor.x, attractor.y, attractor.z) end every 10 ``` -------------------------------- ### Load Iris Dataset with StatsPlots Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/index.md Loads the Iris dataset using RDatasets and imports StatsPlots recipes for DataFrame compatibility. Ensure StatsPlots is installed (`Pkg.add("StatsPlots")`). ```julia # load a dataset using RDatasets iris = dataset("datasets", "iris"); # load the StatsPlots recipes (for DataFrames) available via: # Pkg.add("StatsPlots") using StatsPlots ``` -------------------------------- ### Plotting with Y-Scale Series Recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Example of plotting data using the `yscaleseries` recipe. This demonstrates how the series recipe is applied, but can lead to errors if plot attributes are modified after subplots are built. ```julia yscaleseries((1:10).^2) ``` -------------------------------- ### Add a New Theme Source: https://github.com/juliaplots/plots.jl/blob/v2/PlotThemes/README.md To contribute a new theme, create a `mytheme.jl` file and add the theme definition to the `_themes` dictionary. This involves specifying keyword arguments for Plots attributes. ```julia _themes[:mytheme] = PlotTheme(; kwargs...) ``` -------------------------------- ### Define Custom Marker Shape in Julia Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/basics.md Create a custom marker shape using the `Shape` constructor, which takes a vector of 2-tuples defining polygon points. Example shows a square. ```julia Shape([(1,1),(1,-1),(-1,-1),(-1,1)]) ``` -------------------------------- ### Call User Recipe with Random Data Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Demonstrates calling the custom 'mycount' recipe with a randomly generated array of 500 numbers. ```julia mycount(rand(500)) ``` -------------------------------- ### Handling annotations with font characteristics in Plots.jl Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Annotations in Plots.jl can now accept a Tuple to specify font characteristics, simplifying recipe definitions. This example shows how to specify text, alignment, size, and color. ```julia annotations = (2, 4, ("test", :right, 8, :red)) ``` ```julia annotations = (2, 4, text("test", :right, 8, :red)) ``` -------------------------------- ### Test RecipesBase Package Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Navigate to the root Plots.jl directory and run tests for RecipesBase using a specific project environment. This verifies the functionality of RecipesBase. ```bash $ cd Plots.jl $ julia --project=RecipesBase -e 'using Pkg; Pkg.test()' ``` -------------------------------- ### Preview Plot Theme Source: https://github.com/juliaplots/plots.jl/blob/v2/PlotThemes/README.md Use `Plots.showtheme` to preview the appearance of a specific theme. ```julia Plots.showtheme(thm::Symbol) ``` -------------------------------- ### Switch to PlotlyJS Backend Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/gallery/plotlyjs/index.md Use this command to set PlotlyJS as the active plotting backend. Ensure the Plots package is imported first. ```julia using Plots plotlyjs() ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Use this command sequence to create a new branch for feature development, ensuring you start from the latest master branch. The `-u` flag sets up tracking for the remote branch. ```bash git fetch origin git checkout master git merge --ff-only origin/master git checkout -b user123-myfeature git push -u forked user123-myfeature ``` -------------------------------- ### Override Standard Default Values Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/install.md Customizes standard default plotting values by defining the `PLOTSBASE_DEFAULTS` dictionary in the `~/.julia/config/startup.jl` file. This example sets default marker size, disables the legend, and turns off warnings for unsupported options. ```julia PLOTSBASE_DEFAULTS = Dict(:markersize => 10, :legend => false, :warn_on_unsupported => false) ``` -------------------------------- ### Define a Type Recipe for Composable Wrappers Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Demonstrates how type recipes can compose automatically. This recipe maps `MyOtherWrapper` to its wrapped content, allowing it to work with other recipes. ```julia struct MyOtherWrapper w end @recipe f(::Type{MyOtherWrapper}, mow::MyOtherWrapper) = mow.w ``` -------------------------------- ### Using `=== nothing` for checks Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md This snippet demonstrates the use of `=== nothing` for checking null values, a common pattern in Julia code. ```julia use `=== nothing` ``` -------------------------------- ### Add Custom Data and Legend Sizing in PlotlyJS Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/backends.md Shows how to pass arbitrary arguments to PlotlyJS series and layout dictionaries using `extra_kwargs`. This example adds custom data to scatter points and sets legend item sizing. ```julia pl = scatter( 1:3, rand(3), extra_kwargs = KW( :series => KW(:customdata => ["a", "b", "c"]), :plot => KW(:legend => KW(:itemsizing => "constant")) ) ) ``` -------------------------------- ### User Recipe for Custom Pie Plot Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/RecipesBase/types.md Implements a user recipe to create a pie chart visualization. It extracts data, calculates angles, and draws shapes for each slice. ```julia # defines mutable struct `UserPie` and sets shorthands `userpie` and `userpie!` @userplot UserPie @recipe function f(up::UserPie) y = up.args[end] # extract y from the args # if we are passed two args, we use the first as labels labels = length(up.args) == 2 ? up.args[1] : eachindex(y) framestyle --> :none aspect_ratio --> true s = sum(y) θ = 0 # add a shape for each piece of pie for i in 1:length(y) # determine the angle until we stop θ_new = θ + 2π * y[i] / s # calculate the coordinates coords = [(0.0, 0.0); PlotsBase.partialcircle(θ, θ_new, 50)] @series begin seriestype := :shape label --> string(labels[i]) coords end θ = θ_new end # we already added all shapes in @series so we don't want to return a series # here. (Technically we are returning an empty series which is not added to # the legend.) primary := false () end ``` -------------------------------- ### Create a complex grid layout with custom heights Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/layouts.md Use the `grid(...)` constructor for more complex grid arrangements and specify custom heights for rows. ```julia plot(rand(100, 4); layout = grid(4, 1, heights=[0.1 ,0.4, 0.4, 0.1])) ``` -------------------------------- ### More general tuple recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Enhances the tuple recipe to handle a wider range of input formats. ```julia more general tuple recipe ``` -------------------------------- ### Test PlotsBase Package Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Navigate to the PlotsBase directory and run tests using Julia's Pkg manager. This ensures the PlotsBase components are functioning correctly. ```bash $ cd Plots.jl/PlotsBase $ julia --project=. -e 'using Pkg; Pkg.test()' ``` -------------------------------- ### Plotting with Various Data Structures Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/input_data.md Demonstrates plotting multiple series with custom labels, marker shapes, and colors by combining row and column vectors with matrix data. Ensure Plots is imported and a backend like GR is initialized. ```julia using Plots # 10 data points in 4 series xs = range(0, 2π, length = 10) data = [sin.(xs) cos.(xs) 2sin.(xs) 2cos.(xs)] # we put labels in a row vector: applies to each series labels = ["Apples" "Oranges" "Hats" "Shoes"] # marker shapes in a column vector: applies to data points markershapes = [:circle, :star5] # marker colors in a matrix: applies to series and data points markercolors = [ :green :orange :black :purple :red :yellow :brown :white ] plot( xs, data, label = labels, shape = markershapes, color = markercolors, markersize = 10 ) ``` -------------------------------- ### Plot with LaTeX Strings and MathJax Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/backends.md Demonstrates plotting with LaTeX strings for labels and axes using the PlotlyJS backend. It includes enabling MathJax rendering from a CDN for mathematical expressions. Ensure PlotlyJS is set as the backend. ```julia using LaTeXStrings plotlyjs() plot( 1:4, [[1,4,9,16]*10000, [0.5, 2, 4.5, 8]], labels = [L"\alpha_{1c} = 352 \pm 11 \text{ km s}^{-1}" L"\beta_{1c} = 25 \pm 11 \text{ km s}^{-1}"] |> permutedims, xlabel = L"\sqrt{(n_ ext{c}(t|{T_ ext{early}}))}", ylabel = L"d, r \text{ (solar radius)}", yformatter = :plain, extra_plot_kwargs = KW( :include_mathjax => "cdn", :yaxis => KW(:automargin => true), :xaxis => KW(:domain => "auto") ), ) PlotsBase.html("plotly_mathjax") #hide ``` -------------------------------- ### Create a Basic Line Plot Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/tutorial.md Generates a line plot of a sine wave. Ensure the Plots.jl package is initialized before running. ```julia x = range(0, 10, length=100) y = sin.(x) plot(x, y) ``` -------------------------------- ### Generated Recipe Implementation Source: https://github.com/juliaplots/plots.jl/blob/v2/RecipesBase/README.md This code demonstrates the generated implementation of a plot recipe, including attribute management and series data creation. It uses RecipesBase.apply_recipe to define how custom types are plotted. ```julia function RecipesBase.apply_recipe(d::Dict{Symbol,Any},::T,n=1) begin customcolor = get!(d,:customcolor,:green) end series_list = RecipesBase.RecipeData[] func_return = begin get!(d,:markershape,:auto) d[:markercolor] = customcolor get!(d,:xrotation,45) get!(d,:zrotation,90) rand(10,n) end if func_return !== nothing push!(series_list,RecipesBase.RecipeData(d,RecipesBase.wrap_tuple(func_return))) end begin RecipesBase.is_key_supported(:customcolor) || delete!(d,:customcolor) end series_list end ``` -------------------------------- ### Expanding ~ in paths on UNIX systems Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Ensures that the tilde character (~) in file paths is correctly expanded on UNIX-like systems. ```julia expand ~ in paths on UNIX systems ``` -------------------------------- ### Plotting with DataFrames using StatsPlots Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/input_data.md Demonstrates plotting directly from a DataFrame using the StatsPlots extension. Requires StatsPlots and RDatasets to be loaded. Column names are used as symbols for data fields and attributes like 'group'. ```julia using StatsPlots, RDatasets gr() iris = dataset("datasets", "iris") @df iris scatter( :SepalLength, :SepalWidth; group = :Species, m = (0.5, [:+ :h :star7], 12), bg = RGB(0.2, 0.2, 0.2) ) ``` -------------------------------- ### Using FFMPEG.jl for animations Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Integrates FFMPEG.jl for improved handling and generation of animations. ```julia use FFMPEG.jl ``` -------------------------------- ### Run Pre-commit Checks Manually Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/contributing.md Manually execute all pre-commit checks across all files in the repository. ```bash pre-commit run --all-files ``` -------------------------------- ### Switch to Gaston Backend Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/gallery/gaston/index.md Use this command to switch the plotting backend to Gaston. Ensure Plots is already imported. ```julia using Plots gaston() ``` -------------------------------- ### Apply Thickness Scaling for Presentations Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/attributes.md Use `thickness_scaling` to increase font sizes and linewidths by a factor, which is useful for presentations and posters. If the backend doesn't support it, use `scalefontsizes()`. ```julia scatter(y; thickness_scaling = 2) ``` -------------------------------- ### Marginal Kernel Density Estimation (KDE) Source: https://github.com/juliaplots/plots.jl/blob/v2/StatsPlots/README.md Creates a plot showing the marginal kernel density estimates for two related variables. Useful for visualizing bivariate distributions. ```julia x = randn(1024) y = randn(1024) marginalkde(x, x+y) ``` -------------------------------- ### Create a Color Gradient with Color Transitions Source: https://github.com/juliaplots/plots.jl/blob/v2/docs/src/colorschemes.md Construct a color gradient with specified transition points. The second argument is a vector of values between 0 and 1 indicating where color changes occur. ```julia cgrad([:orange, :blue], [0.1, 0.3, 0.8]) ``` -------------------------------- ### Asymmetric Violin and Dot Plots Source: https://github.com/juliaplots/plots.jl/blob/v2/StatsPlots/README.md Demonstrates creating asymmetric violin and dot plots by specifying the `side` keyword argument (`:left` or `:right`) to visualize distributions on one side. ```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="") ``` -------------------------------- ### Adding Char recipe Source: https://github.com/juliaplots/plots.jl/blob/v2/NEWS.md Introduces a new recipe for plotting data of type `Char`. ```julia add Char recipe ```