P. Denelle
P. Denelle

Reputation: 830

R plotly, have different color and z-axis on 3D heatmap

I want to plot a 3D heatmap with plotly but I would like to have the color gradient independent of the z-axis.

With ggplot2 I can produce the following image:

dat <- data.frame("cat1" = sort(rep(seq(1:6), 6)),
                  "cat2" = rep(seq(1:6), 6),
                  "variable" = round(rnorm(36), 1),
                  "freq" = seq(100, (100-35)))

library(ggplot2)
ggplot(data.frame(dat), aes(cat1, cat2, fill = variable, label = freq)) + 
  geom_tile() +
  geom_text()

enter image description here

And now with plotly, I'm unable to have the height related to one column (here freq) and the color to another one (column variable). The following image relates both height and color to freq.

library(plotly)
mat <- tapply(dat$freq, list(dat$cat1, dat$cat2), sum)
plot_ly(z = ~ mat) %>% add_surface

enter image description here

Upvotes: 1

Views: 1396

Answers (2)

P. Denelle
P. Denelle

Reputation: 830

Based on @MLavoie suggestion, I found a way to decorrelate color and height of the 3D heatmap.

dat <- data.frame("cat1" = sort(rep(seq(1:6), 6)),
                  "cat2" = rep(seq(1:6), 6),
                  "variable" = round(rnorm(36), 1),
                  "freq" = seq(100, (100-35)))
library(plotly)
mat <- tapply(dat$freq, list(dat$cat1, dat$cat2), sum)
mat_col <- tapply(dat$variable, list(dat$cat1, dat$cat2), sum)

plot_ly(z = ~ mat, type = "surface", surfacecolor = mat_col)

enter image description here

Upvotes: 0

MLavoie
MLavoie

Reputation: 9836

Are you looking for something like this?

plot_ly(z=~mat, type="surface", surfacecolor = matrix(nrow = 6, ncol = 6, rep(1:6, each = 6))

I think with surfacecolor you can get what you want.

Upvotes: 1

Related Questions