Skip to content

Instantly share code, notes, and snippets.

@ssfrr
Last active February 8, 2018 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssfrr/089c670a860a36fcb5c6fc92c3fef7ea to your computer and use it in GitHub Desktop.
Save ssfrr/089c670a860a36fcb5c6fc92c3fef7ea to your computer and use it in GitHub Desktop.
using PlotlyJS
# SVG Path construction
addmove!(io, x, y) = write(io, "M $x $y")
addlineto!(io, x, y) = write(io, " L $x $y")
addclose!(io) = write(io, " Z")
"""
Makes a set of connected lines that go through the points defined by xs and ys
by adding the appropriate SVG commands to the given IO.
"""
function lines!(io, xs, ys)
if length(xs) < 2 || length(ys) < 2
error("x and y vectors must be at least length 2")
end
addmove!(io, xs[1], ys[1])
for i in 2:min(length(xs), length(ys))
addlineto!(io, xs[i], ys[i])
end
end
"""
Make a polygon with a boundary defined by the given points.
returns a path shape
"""
function polygon(xs, ys; kwargs...)
io = IOBuffer()
lines!(io, xs, ys)
svg = String(take!(io))
path(svg; kwargs...)
end
"""
corners(X, row, col)
Returns the x and y coordinates of the 4 corners of the given cell of the matrix
X.
"""
function corners(X, row, col)
indices = [(row, col), (row+1, col), (row+1, col+1), (row, col+1), (row, col)]
elems = [X[I...] for I in indices]
xs = real.(elems)
ys = imag.(elems)
xs, ys
end
"""
colorsquares(X; kwargs...)
Create colored polygons for each cell of the matrix X, returned as a list.
"""
function colorsquares(X; kwargs...)
# we have one fewer rows/cols of squares than we do of points
nrows = size(X, 1)-1
ncols = size(X, 2)-1
squares = []
for row in 1:nrows, col in 1:ncols
color = if row <= nrows ÷ 2
if col <= ncols ÷ 2
:red
else
:green
end
else
if col <= ncols ÷ 2
:blue
else
:yellow
end
end
push!(squares, polygon(corners(X, row, col)...; fillcolor=color, kwargs...))
end
squares
end
# generate a grid in the complex plane
X = [a+b*im for b in linspace(-1.1, 1.1, 21), a in linspace(-1.1, 1.1, 21)]
# transform the grid
X2 = 0.1X.^3 + 0.4X.^2+0.4X
# create the axes
p = hcat(
plot(scatter(), Layout(xaxis_range=(-2.1, 2.1), yaxis_range=(-2.1, 2.1))),
plot(scatter(), Layout(xaxis_range=(-2.1, 2.1), yaxis_range=(-2.1, 2.1))))
# add the shapes
relayout!(p,
shapes=vcat(colorsquares(X, xref="x1", yref="y1", opacity=0.7),
colorsquares(X2, xref="x2", yref="y2", opacity=0.7)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment