Plot Attributes in Makie.jl - plot

I'd like to plot a function f(x,y,z) in xyz-space by HeatMap.
I have the following code by https://lazarusa.github.io/BeautifulMakie/surfWireLines/RGBcube/ .
using GLMakie, GeometryBasics, Colors
positions = vec([(i, j, k) for i=1:L,j=1:L,k=1:L]) #3D coordinate
F = zeros(Float64,length(positions)
for i = 1:length(positions) #convert f(x,y,z) to an array
x = positions[i][1]
y = positions[i][2]
z = positions[i][3]
   F[i] = f(x,y,z)
end
fig, ax = mesh(HyperRectangle(Vec3f0(positions[1]...),Vec3f0(0.8)), color = RGBA(0,0,F[1],0.5), transparency = false) #HyperRectangle(::position,::length),color=(::red,::green,::blue,::alpha)
wireframe!(ax,HyperRectangle(Vec3f0(positions[1]...), Vec3f0(0.8)), linewidth = 0.1, overdraw = false)
for i in 2:length(positions)
mesh!(ax, HyperRectangle(Vec3f0(positions[i]...), Vec3f0(0.8)), color = RGBA(0,0,F[i],0.5))
wireframe!(ax, HyperRectangle(Vec3f0(positions[i]...), Vec3f0(0.8)), linewidth = 0.1, overdraw = false)
end
fig
This code has mostly helped, but there's still a little problem.:
How to move the camera? (update_camera! needs Scene, but ax is LScene. I don't know what this is.)
How to adjust the axis (labels, ticks, etc.)?
How to add the colorbar?
How to save the figure?

again.
I did another example. This one is really fast. There, you have most of the options you want.
https://lazarusa.github.io/BeautifulMakie/surfWireLines/volumeScatters/
For custom ticks, you can always do
ax.xticks = ([1,2,3], ["1","2", "3"])
also, consider joining https://discourse.julialang.org, there more people could help, much much faster.
Complete code here as well.
# by Lazaro Alonso
using GLMakie
let
x = 1:10
y = 1:10
z = 1:10
f(x,y,z) = x^2 + y^2 + z^2
positions = vec([(i, j, k) for i in x,j in y, k in z])
vals = [f(ix,iy,iz) for ix in x, iy in y, iz in z]
fig, ax, pltobj = meshscatter(positions, color = vec(vals),
marker = FRect3D(Vec3f0(0), Vec3f0(10)), # here, if you use less than 10, you will see smaller squares.
colormap = :Spectral_11, colorrange = (minimum(vals), maximum(vals)),
transparency = true, # set to false, if you don't want the transparency.
shading= false,
figure = (; resolution = (800,800)),
axis=(; type=Axis3, perspectiveness = 0.5, azimuth = 7.19, elevation = 0.57,
xlabel = "x label", ylabel = "y label", zlabel = "z label",
aspect = (1,1,1)))
cbar = Colorbar(fig, pltobj, label = "f values", height = Relative(0.5))
xlims!(ax,-1,11)
ylims!(ax,-1,11)
zlims!(ax,-1,11)
fig[1,2] = cbar
fig
#save("fileName.png", fig) # here, you save your figure.
end

Related

How to plot 3D HeatMap in Julia?

I want to plot 3D HeatMap for 3D function f(x,y,z).
For 2D function f(x,y), I know the below code works.
using Plots
x = 1:L # coordinate range
y = 1:L
F = Float64[f(ix,iy) for ix in x, iy in y]' #convert f(x,y) to an array
plot(F,st=:heatmap,color= cgrad(:blues))
plot!(xlabel="x",ylabel="y",aspect_ratio=:equal)
plot!(xlims=(1,L),ylims=(1,L))
For 3D function, where should I change?
using Plots
x = 1:L # coordinate range
y = 1:L
z = 1:L
F = Float64[f(ix,iy,iz) for ix in x, iy in y,iz in z] #convert f(x,y,z) to an array
plot(F,st=:heatmap,color = cgrad(:blues),alpha=0.1)
plot!(xlabel="x",ylabel="y",zlabel="z",aspect_ratio=:equal)
plot!(xlims=(1,L),ylims=(1,L),zlims=(1,L))
This code passes, but something is wrong.
color = cgrad(:blues),alpha=0.1,xlabel="x",ylabel="y" are not reflected.
In addition, the figure does not seem to be f(x,y,z). For example, f(x,y,z) = x^2 + y^2 +z^2 gives a spherical gradation, but the result is not.
The above approach is slow for more data points. However, I think you don't want heatmaps as the heatmaps in the previous link are just projections from 2D into 3D planes.
I think you need something like this.
See code here.
https://lazarusa.github.io/BeautifulMakie/surfWireLines/volume/
See image
And for convenience also here:
using GLMakie
let
x = 1:10
y = 1:10
z = 1:10
f(x,y,z) = x^2 + y^2 + z^2
vol = [f(ix,iy,iz) for ix in x, iy in y, iz in z]
fig, ax, _ = volume(x, y, z, vol, colormap = :plasma,colorrange = (minimum(vol), maximum(vol)),
figure = (; resolution = (800,800)),
axis=(; type=Axis3, perspectiveness = 0.5, azimuth = 7.19, elevation = 0.57,
aspect = (1,1,1)))
fig
end
3D HeatMap by Makie.jl
I don't know how to plot 3D HeatMap by Plots.jl yet, but I found the another way by Makie.jl : https://lazarusa.github.io/BeautifulMakie/surfWireLines/RGBcube/ .
With the help of this sample code, I got the following code.
using GLMakie, GeometryBasics, Colors
positions = vec([(i, j, k) for i=1:L,j=1:L,k=1:L]) #3D coordinate
F = zeros(Float64,length(positions)
for i = 1:length(positions) #convert f(x,y,z) to an array
x = positions[i][1]
y = positions[i][2]
z = positions[i][3]
   F[i] = f(x,y,z)
end
fig, ax = mesh(HyperRectangle(Vec3f0(positions[1]...),Vec3f0(0.8)), color = RGBA(0,0,F[1],0.5), transparency = false) #HyperRectangle(::position,::length),color=(::red,::green,::blue,::alpha)
wireframe!(ax,HyperRectangle(Vec3f0(positions[1]...), Vec3f0(0.8)), linewidth = 0.1, overdraw = false)
for i in 2:length(positions)
mesh!(ax, HyperRectangle(Vec3f0(positions[i]...), Vec3f0(0.8)), color = RGBA(0,0,F[i],0.5))
wireframe!(ax, HyperRectangle(Vec3f0(positions[i]...), Vec3f0(0.8)), linewidth = 0.1, overdraw = false)
end
fig

Changing axis displays for a graph using plot3D in R?

I'm hoping to keep in the image below the ticks on the vertical z axis, but remove ticks and numbers from the x and y axes. I would like to be able to label my x and y axes with a label for each condition in my matrix, but have not figured out how to do this with text3D. For some reason (because I'm on a mac?) I can't download axes3D, which is one potential solution I've seen in other responses.
Here is my code:
x = c(0,1)
y = c(0,1)
zval = c(104.1861, 108.529, 110.3675, 110.4112)
z = matrix (zval, nrow=2, ncol=2, byrow=TRUE)
hist3D(x,y,z, zlim=c(101,111), colvar = NULL, d=2, col = "lightblue", NAcol = "white", breaks = NULL, colkey = NULL, theta=-60, phi=20, nticks=10, axes=TRUE, ticktype="detailed", space=0.5, lighting=TRUE, light="diffuse", shade=.5, ltheta = 50, bty = "g")
My output

Ultimately, I'd like something more along the lines of this:
I'm very new to R.
stackoverflow.com/questions/26794236/ggplot2-3d-bar-plot
^ this seems like it might be what I need, but I couldn't replicate the code without an error. When I tried to run this piece I got an error because my x and z (in this case) axes aren't numerical:
cloud(y~x+z, d, panel.3d.cloud=panel.3dbars, col.facet='grey', xbase=0.4, ybase=0.4, scales=list(arrows=FALSE, col=1), par.settings = list(axis.line = list(col = "transparent")))
Maybe this might be helpful (with the caveat that 3D plots can sometimes make interpretation more challenging).
First, I recreated a data frame d based on something similar to what you started with:
x = c(0, 0, 1, 1)
y = c(0, 1, 0, 1)
z = c(104.1861, 108.529, 110.3675, 110.4112)
d <- data.frame(
x = factor(as.logical(x)),
y = factor(as.logical(y)),
z = z
)
Note that for x and y I converted the 0 and 1 to FALSE and TRUE with as.logical, then made them factors.
Then for the plot:
library(latticeExtra)
cloud(z ~ x + y, data = d, panel.3d.cloud=panel.3dbars, col.facet='grey',
xbase=0.4, ybase=0.4, scales=list(arrows=FALSE, col=1),
par.settings = list(axis.line = list(col = "transparent")))
You will want the formula as z ~ x + y where z is a numeric response.
Edit: If you wish to customize the axis labels, you can set the factor labels as follows (for example):
d <- data.frame(
x = factor(as.logical(x), labels = c("Hi", "Lo")),
y = factor(as.logical(y), labels = c("Label1", "Label2")),
z = z
)
Plot

Add a line that indicates the average value of an axis in a plotly scatterplot [duplicate]

I'm using the plotly package and I'm trying to add a horizontal line to a graph. Is there any way of doing it using plotly?
It can be done using ggplot2 and the ggplotly function as shown below:
library(plotly)
p <- ggplot() +
geom_hline(yintercept = 4) +
xlim(c(0,10)) +
ylim(c(0,10))
ggplotly(p)
But I can't add this to an existing plotly plot.
Also, the axis of my charts are not fixed, so it would be difficult (but not impossible) to just work out an x and y coordinate system for a horizontal line, but I'd rather just add one automatically.
I've looked into the y0 and dy arguments, but I can't seem to get the code for those to work, either. I'm not quite sure what they do exactly, but I think they're maybe what I'm looking for? I can't find good examples of their usage.
There are two main ways to do this (using either data or 'paper' coordinates). Assuming data coordinates, the easiest current way is via add_segments():
plot_ly() %>%
add_segments(x = 4, xend = 4, y = 0, yend = 10) %>%
add_segments(x = 3, xend = 5, y = 5, yend = 5)
Notice how we've hard coded the extent of these lines in data coordinates; so when zooming and panning the plot, the line will be "clipped" at those values. If you don't want these lines to be clipped, use a line shape with xref/yref set to paper (this puts the graph region on a 0-1 scale, rather than on the x/y data scale):
vline <- function(x = 0, color = "red") {
list(
type = "line",
y0 = 0,
y1 = 1,
yref = "paper",
x0 = x,
x1 = x,
line = list(color = color)
)
}
hline <- function(y = 0, color = "blue") {
list(
type = "line",
x0 = 0,
x1 = 1,
xref = "paper",
y0 = y,
y1 = y,
line = list(color = color)
)
}
plot_ly() %>%
layout(shapes = list(vline(4), hline(5)))
Alternatively, you could add a shape (i.e. line) under layout(). The following example adds a vertical line:
p <- plot_ly(data, x = ~x.data, y = ~y.data, text = ~text.data, type = 'scatter',
mode = 'markers', marker = list(size = ~size.data, opacity= 0.5)) %>%
layout(shapes=list(type='line', x0= 0.2, x1= 0.2, y0=min(allyvalues), y1=max(allyvalues), line=list(dash='dot', width=1)),
title = 'This is the Title',
xaxis = list(title = "X-Axis", showgrid = TRUE),
yaxis = list(title = "Y-Axis", showgrid = TRUE))
p
Building on Carson's nice answer above, here is a convenience function closer to ggplot's geom_vline()
# Add vertical line(s) at position x to plotly plot p
# Additional arguments: color, width (px), dash ('solid','dot', 'dash', etc)
# See https://plotly.com/r/reference/#layout-shapes-items-shape-line
add_vline = function(p, x, ...) {
l_shape = list(
type = "line",
y0 = 0, y1 = 1, yref = "paper", # i.e. y as a proportion of visible region
x0 = x, x1 = x,
line = list(...)
)
p %>% layout(shapes=list(l_shape))
}
To make the function additive the following modifications to the function can be used
add_vline = function(p, x, ...) {
if(!is.null(p$x$layoutAttrs)){
index <- unname(which(sapply(p$x$layoutAttrs, function(x)
!is.null(x$shapes))))
} else {
index <- integer()
}
l_shape = list(
type = "line",
y0 = 0, y1 = 1, yref = "paper", # i.e. y as a proportion of visible region
x0 = x, x1 = x,
line = list(
...
),
layer = "below"
)
if(length(index) > 0){
shapes <- p$x$layoutAttrs[[index]]$shapes
shapes[[length(shapes) + 1]] <- l_shape
p$x$layoutAttrs[[index]]$shapes <- shapes
} else {
p <- plotly::layout(
p = p,
shapes = list(l_shape)
)
}
p
}

display point labels in scatter3d

I plotted a 3d scatter plot in R using the scatter3d function.
Now, I want to plot the labels on every dot in the 3d scatter, such as every point has its ID next to it i.e., "1", "2" etc..
Here is what I tried:
library("car")
library("rgl")
scatter3d(geometry[,1],geometry[,2],geometry[,3] , surface=FALSE, labels = rownames(geometry), id.n=nrow(geometry))
This tutorial says that adding arguments labels=rownames(geometry), id.n=nrow(geometry) should display the labels on every dot but that did not work.
EDIT:
I uploaded the coordinate file here, you can read it like this
geometry = read.csv("geometry.txt",sep = " ")
colnames(geometry) = c("x","y","z")
EDIT:
Actually, even the example from the tutorial does not label the points and does not produce the plot displayed. There is probably something wrong with the package.
scatter3d(x = sep.l, y = pet.l, z = sep.w,
surface=FALSE, labels = rownames(iris), id.n=nrow(iris))
I can give you a quick fix if you want to use any other function other than scatter3d. This can be achieved using plot3d and text3d function. I have provided the basic code block of how it can be implemented. You can customize it to your needs.
plot3d(geometry[,1],geometry[,2],geometry[,3])
text3d(geometry[,1],geometry[,2],geometry[,3],rownames(geometry))
points3d(geometry[,1],geometry[,2],geometry[,3], size = 5)
After much messing around I got it (I also have the method for plot_ly if you,re interested)
test2 <- cbind(dataSet[,paste(d)],set.final$Groups,test)
X <- test2[,1]
Y <- test2[,2]
Z <- test2[,3]
# 3D plot with the regression plane
scatter3d(x = X, y = Y, z = Z, groups = test2$`set.final$Groups`,
grid = FALSE, fit = "linear",ellipsoid = FALSE, surface=FALSE,
surface.col = c("green", "blue", "red"),
#showLabels(x = x, y = y, z = z, labels=test2$test, method="identify",n = nrow(test2), cex=1, col=carPalette()[1], location=c("lr"))
#labels = test2$test,
id=list(method = "mahal", n = length(test2$test), labels = test2$test)
#id.n=nrow(test2$test)
)
#identify3d(x = X, y = Y, z = Z, labels = test2$test, n = length(test2$test), plot = TRUE, adj = c(-0.1, 0.5), tolerance = 20, buttons = c("right"))
rglwidget()

Complete missing lines using rgl grid3d

Does anyone know of a way to 1) complete the missing gridlines in the grid3d call for y, and 2) draw horizontal gridlines to close the top of the grids constructed by the grid3d calls for x and y? I've played around with various combinations of pretty calls within grid3d to no avail and am wondering if this is an rgl quirk or a misspecification on my part. Additionally, I'd like to extend the vertical axis numbering to wherever the closed grids end up.
library(rgl)
cpts <- seq(0, 2, length = 40)
spts <- seq(0, 1, length = 20)
grid <- expand.grid(s=spts, c=cpts)
UFn <- function(s,c){c^(0.5) - exp(s) + 1}
U <- UFn(grid$s, grid$c)
open3d()
rgl.surface(x = spts, y = matrix(U,nrow = 40, ncol = 20), z = cpts,
coords = c(1,3,2), specular = "black")
axes3d("x", at = pretty(spts, n = 2), color = "black")
axes3d("y", at = pretty(cpts, n = 5), color = "black")
axes3d("z--", color = "black")
grid3d("x")
grid3d("y", at = pretty(spts, n = 2))
title3d(xlab ='s', ylab = 'c', zlab = 'U', color = "black")
rgl.snapshot("3d.png")
I would say it is a bug. You don't get any z-lines when using grid3d("y",n=2) even though it should be the same. You can work around it by using the list specification of at, setting the x element of the list, eg:
grid3d("y", at = list(x=pretty(spts, n = 2)))

Resources