I want to plot a matrix in R with plotly, where the color scale is to be based on quantile values. Here is a self-contained reproducible example:
library(dplyr)
library(plotly)
# Data to plot
d <- data.frame(x = 1:10, y=1:10, z = rnorm(n = 10, mean = 0, sd = 100))
# Quantile values
qtl_val <- c(0, 0.68, 0.95, 0.99, 0.997)
# Colors to use
qtl_colors <- c(
rgb(0,0,0),
rgb(246/256,192/256,192/256),
rgb(244/256,135/256,134/256),
rgb(219/256,55/256,55/256),
rgb(164/256,30/256,34/256))
# Function to assign a color to each quantile window
set_color <- function(z,qtl_leg){
for( i in 1:nrow(qtl_leg)){
min_val <- qtl_leg$val[i]
max_val <- ifelse( !is.na(qtl_leg$lead_val[i]), qtl_leg$lead_val[i], Inf)
if( z >= min_val & z <= max_val ) return(qtl_leg$color[i])
}
}
qtl_leg <- data.frame(val=round(as.numeric(quantile(d$z, probs=qtl_val)))) %>%
mutate(lead_val = lead(val)) %>%
mutate(color = qtl_colors)
d <- d %>%
rowwise() %>%
mutate(color = set_color(z,qtl_leg) ) %>%
as.data.frame()
# Draw the matrix
plot_ly(data=d, x=~x, y=~y, z=~z, color=~color, type='heatmap' )
The plot does not match the colors set in the data.frame, the legend is weird and the tip-tool text as well. In a nutshell, I got something wrong but I don't figure out what.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.