(Yes, I know the topic is 4-years-old)
I’ve asked a couple of AIs this question, was each time told “good children don’t do it, but if you want…”. That’s one of the solutions I found practical, reviewed and fixed:
In AlgebraOfGraphics.jl, there is no direct high-level keyword to produce a dual-axis plot because the “Grammar of Graphics” philosophy generally discourages them.
However, because the package is built on Makie.jl, you can achieve this by creating two overlapping axes in the underlying Makie Figure and drawing separate AlgebraOfGraphics layers into them.
Here is how to do it:
The Solution: Overlaying Makie Axes
You must create a Makie Figure manually, place two Axis objects in the same grid position (one with the Y-axis on the right), and then use draw! to plot your datasets into each specific axis.
using AlgebraOfGraphics, WGLMakie
# 1. Prepare Data
d1 = (x = 1:10, y = rand(10) .* 10) # Dataset 1 (Scale A)
d2 = (x = 1:11, y = rand(11) .* 1000) # Dataset 2 (Scale B, much larger, also differing X-range)
# 2. Define your AlgebraOfGraphics specs (layers)
# Important: Do not combine them with `+`. Keep them as separate layers.
layer1 = data(d1) * mapping(:x, :y) * visual(Lines, color=:blue)
layer2 = data(d2) * mapping(:x, :y) * visual(Scatter, color=:red)
# 3. Create a Makie Figure and Axes
fig = Figure()
xlimits = (0, 12) # ensure both plots have the same X-scale
# Create the first axis (Left Y-axis)
ax1 = Axis(fig[1, 1],
ylabel = "Scale A (Blue)",
yticklabelcolor = :blue,
limits = (xlimits, (0, 10)), # optionally manually setting Y-axis limits
)
# Create the second axis (Right Y-axis) in the SAME grid position
# set `yaxisposition = :right` and ensure the background is transparent
ax2 = Axis(fig[1, 1],
ylabel = "Scale B (Red)",
yaxisposition = :right,
yticklabelcolor = :red,
backgroundcolor = :transparent,
limits = (xlimits, (0, 1000)),
)
# Optional: Hide the spines of the second axis so they don't overlap awkwardly
hidespines!(ax2, :l, :b, :t)
hidexdecorations!(ax2) # Hide x-ticks of the secondary axis to avoid clutter
# 4. Draw the layers into the specific axes
draw!(ax1, layer1)
draw!(ax2, layer2)
# Display the result
fig
Key Steps Explained:
- Separate Layers: Unlike a standard AoG plot where you combine layers with +, here you keep layer1 and layer2 separate so you can direct them to different axes.
- yaxisposition = :right: This Makie attribute moves the ticks and label of the second axis to the right side.
- backgroundcolor = :transparent: The second axis is drawn on top of the first. If you don’t make it transparent, it will block the view of the first plot.
- draw!(ax, layer): The mutating draw! function allows you to render an AlgebraOfGraphics specification directly into an existing Makie axis.