Putting it Together

We will now look at how to combine traces and a layout to create a plot.

We'll also discuss how to integrate with various frontends.

Plot

Recall that the definition of the Plot object is

mutable struct Plot{TT<:AbstractVector{<:AbstractTrace},TL<:AbstractLayout,TF<:AbstractVector{<:PlotlyFrame}}
    data::TT
    layout::TL
    frames::TF
    divid::UUID
    config::PlotConfig
end

Given one or more AbstractTraces and optionally a Layout, we construct a Plot object with any of the following constructors

# A blank canvas no traces or a layout
Plot()

# A vector of traces and a layout
Plot{T<:AbstractTrace}(data::AbstractVector{T}, layout::AbstractLayout)

# A vector of traces -- default layout supplied
Plot{T<:AbstractTrace}(data::AbstractVector{T})

# a single trace: will be put into a vector -- default layout supplied
Plot(data::AbstractTrace)

# a single trace and a layout (trace put into a vector)
Plot(data::AbstractTrace, layout::AbstractLayout)

Notice that none of the recommended constructors have you pass the divid field manually. This is an internal field used to allow the display and unique identification of multiple plots in a single web page.

Convenience methods

There are also a number of convenience methods to the Plot function that will attempt to construct the traces for you. They have the following signatures

PlotlyBase.PlotType
Plot(x, y; ...)
Plot(x, y, l; kind, config, kwargs...)

Build a plot of with one trace of type kindand set x to x and y to y. All keyword arguments are passed directly as keyword arguments to the constructed trace.

NOTE: If y is a matrix, one trace is constructed for each column of y

NOTE: If x and y are both matrices, they must have the same number of columns (say N). Then N traces are constructed, where the ith column of x is paired with the ith column of y.

source
Plot(y; ...)
Plot(y, l; kwargs...)

Build a scatter plot and set y to y. All keyword arguments are passed directly as keyword arguments to the constructed scatter.

source
Plot(f, x0, x1; ...)
Plot(f, x0, x1, l; config, kwargs...)

Construct a plot of f from x0 to x1, using the layout l. All keyword arguments are applied to the constructed trace.

source
Plot(fs, x0, x1; ...)
Plot(fs, x0, x1, l; config, kwargs...)

For each function in f in fs, construct a scatter trace that plots f from x0 to x1, using the layout l. All keyword arguments are applied to all constructed traces.

source
Plot(df; ...)
Plot(
    df,
    l;
    category_orders,
    labels,
    facet_row,
    facet_row_wrap,
    facet_col,
    facet_col_wrap,
    group,
    symbol,
    color,
    line_dash,
    kw...
)

Construct a plot using the columns of df if possible. For each keyword argument, if the value of the argument is a Symbol and the df has a column whose name matches the value, replace the value with the column of the df.

If group is passed and is a Symbol that is one of the column names of df, then call by(df, group) and construct one trace per SubDataFrame, passing all other keyword arguments. This means all keyword arguments are passed applied to all traces

All keyword arguments are passed directly to the trace constructor, with the following exceptions:

  • category_orders: A mapping from DataFrame column name to a vector of values that appear in that column. Wherever the column is used in the chart (facets, x, y, etc.) the chart elements tied to the column will be sorted according to the vector of values specified here. This ordering can be partial, in which case all elements that appear in the DataFrame, but not in the vector of values specified here, will be included after values explicitly listed here.
  • labels: A mapping from column names (symbols) to text that should appear on the chart. This can be used to customize the title of axes, title of legend, etc.
  • facet_row: A symbol denoting which DataFrame column should be used to create facetted subplots in the vertical direction.
  • facet_col: A symbol denoting which DataFrame column should be used to create facetted subplots in the horizontal direction.
  • symbol: A symbol noting which column should be used for the marker symbol. The values of this column are not used directly, but rather a new trace will be created for each unique value in this column. Each trace will have a different marker symbol, such as circle, diamond, square, etc.
  • color: Similar to symbol, but for the color of a trace
  • line_dash: Similar to symbol, but for the line style of a trace.
source
Plot(d, x, y; ...)
Plot(d, x, y, l; kwargs...)

Construct a plot from df, passing the provided values of x and y as keyword arguments. See docstring for other method for more information.

source
Plot(d, y; ...)
Plot(d, y, l; kwargs...)

Construct a plot from df, passing the provided value y as a keyword argument. See docstring for other method for more information.

source

Especially convenient is the group keyword argument when calling Plot(::AbstractDataFrame, ... ; ...). Here is an example below:

using RDatasets
iris = RDatasets.dataset("datasets", "iris");
p = Plot(iris, x=:SepalLength, y=:SepalWidth, mode="markers", marker_size=8, group=:Species)
Example block output

SyncPlots

A Plot is a pure Julia object and doesn't interact with plotly.js by itself. This means that we can't view the actual plotly figure the data represents.

To do that we need to link the Plot to one or more display frontends.

To actually connect to the display frontends we use the WebIO.jl package. Our interaction with WebIO is wrapped up in a type called SyncPlot that is defined as follows:

mutable struct SyncPlot
    plot::PlotlyBase.Plot
    scope::Scope
    window::Union{Nothing,Blink.Window}
end

As its name suggests, a SyncPlot will keep the Julia representation of the a plot (the Plot instance) in sync with a plot with a frontend.

Note

The Plot function will create a new Plot object and the plot function will create a new SyncPlot. The plot function passes all arguments to construct a Plot and then sets up the display. All Plot methods are also defined for plot

By leveraging WebIO.jl we can render our figures anywhere WebIO can render. At time of writing this includes Jupyter notebooks, Jupyterlab, Mux.jl web apps, the Juno Julia environment inside the Atom text editor, and Electron windows from Blink.jl. Please see the WebIO.jl readme for additional (and up to date!) information.

When using PlotlyJS.jl at the Julia REPL a plot will automatically be displayed in an Electron window. This is a dedicated browser window we have full control over. To see a plot p, just type p by itself at the REPL and execute the line. Alternatively you can call display(p).

In addition to being able to see our charts in many front-end environments, WebIO also provides a 2-way communication bridge between javascript and Julia. In fact, when a SyncPlot is constructed, we automatically get listeners for all plotly.js javascript events. What's more is that we can hook up Julia functions as callbacks when those events are triggered. In the very contrived example below we have Julia print out details regarding points on a plot whenever a user hovers over them on the display:

using WebIO
p = plot(rand(10, 4));
display(p)  # usually optional

on(p["hover"]) do data
    println("\nYou hovered over", data)
end

In this next example, whenever we click on a point we change its marker symbol to a star and marker color to gold:

using WebIO
colors = (fill("red", 10), fill("blue", 10))
symbols = (fill("circle", 10), fill("circle", 10))
ys = (rand(10), rand(10))
p = plot(
    [scatter(y=y, marker=attr(color=c, symbol=s, size=15), line_color=c[1])
    for (y, c, s) in zip(ys, colors, symbols)]
)
display(p)  # usually optional

on(p["click"]) do data
    colors = (fill("red", 10), fill("blue", 10))
    symbols = (fill("circle", 10), fill("circle", 10))
    for point in data["points"]
        colors[point["curveNumber"] + 1][point["pointIndex"] + 1] = "gold"
        symbols[point["curveNumber"] + 1][point["pointIndex"] + 1] = "star"
    end
    restyle!(p, marker_color=colors, marker_symbol=symbols)
end

While completely nonsensical, hopefully these examples show you that it is possible to build rich, interactive, web-based data visualization applications with business logic implemented entirely in Julia!.

Display configuration

Note

New in PlotlyBase version 0.6.4 (PlotlyJS version 0.16.3)

When calling plot or Plot, we can specify some configuration options using the config keyword argument.

The config argument must be set to an instance of PlotConfig, which should be constructed using keyword arguments.

As an example, if we were to execute the following code, we would see a static chart (no hover information or ability to zoom/pan) with 4 lines instead of an interactive one:

Plot(rand(10, 4), config=PlotConfig(staticPlot=true))

See the API docs for PlotConfig for a full list of options.