Plots.jl
Plots.jl copied to clipboard
[FR] 3D plots for plotly and GR using the same data structure
Let's start our julia file with
using Plots
gr()
Let's say we have a series of data that is given like this:
f(x) = 1/(x^2 + 1)
xs = -10:0.1:10
h = collect(-2:1:2)
ys = @. sign(h) * h^2
y = [f(x - y) for x in xs, y in ys]
plot(xs, y)
Now we want to plot this in 3D and make it look nice. So the first thing that I would do is to use the already generated data and promote the plot to 3D via
X = [x for x in xs, _ in ys]
Y = [y for _ in xs, y in ys]
Z = y
plot(X, Y, Z)
which works nicely for plotly and gr equally. Now let's say we want to promote what we have to a surface plot. First in plotly. This should be straightforward by using
plotly()
surface(X,Y,Z)
which looks nice, but when we use
gr()
surface(X,Y,Z)
we get pitures from a fever dream. The problem is that gr expects a different format for surface
and can't handle the data structure. I guess that messes up the interpolation. We can fix that by using
X_gr = [x for x in xs for _ in ys]
Y_gr = [y for _ in xs for y in ys]
Z_gr = [f(x - y) for x in xs for y in ys]
This is unfortunately not just the vector reshaping of the original data, since it also involves changing the order of the dimensions. To make clear what I mean, this function can also fix it:
function plotly_to_gr(x)
reshape(permutedims(x, [2,1]), prod(size(x)))
end
gr()
surface(plotly_to_gr(X),plotly_to_gr(Y),plotly_to_gr(Z))
The same is true for scatter3d
, I haven't checked other functions. I use Julia 1.9.2 and Plots v1.38.16.
From my point of view it is more logical to have it the way plotly does it. But it might just be me.