I am trying to make an interactive heatmap in R using a combination of geom_tile and ggplotly. However, when I run the ggplotly command, the interactive heatmap I get back only has grey values. Moreover, the interactive hover only seems to work for some values in the heatmap.
Some more information about the data
The data consists of a data frame of 128 rows x 288 columns of values between 0 - 1 at 0.2 increments.
The data can be replicated using the following code:
library(magrittr)
data <- as.data.frame(matrix(data = sample(seq(0, 1, 0.2),
size = 128*288,
replace = TRUE),
nrow = 128,
ncol = 288))
colnames(data) <- seq(1, 288, 1)
data <- data %>%
dplyr::mutate(y_axis = seq(1, 128, 1)) %>%
reshape2::melt(id = "y_axis") %>%
dplyr::rename(x_axis = "variable")
Some more information about the plotting:
I specified the color palette by first producing a color vector as follows
color_vector <- viridis::viridis(
length(
sort(
unique(
unlist(df)))),
direction = 1,
option = "A")
I then made the plot as follows:
plot <-
ggplot2::ggplot(
df, ggplot2::aes(x_axis,
y_axis,
fill=z_axis,
color=z_axis)) +
ggplot2::geom_tile() +
ggplot2::scale_fill_gradientn(
colors = color_vector,
na.value = "grey45",
guide = ggplot2::guide_legend(
title.position = "top",
title.vjust = 1,
title.hjust = 0.5,
nrow=1,
keywidth = grid::unit(5, "mm")),
breaks=seq(0, 1, 0.1),
limits = c(0, 1)) +
ggplot2::scale_color_gradientn(
colors = color_vector,
na.value = "grey45",
guide = ggplot2::guide_legend(
title.position = "top",
title.vjust = 1,
title.hjust = 0.5,
nrow=1,
keywidth = grid::unit(5, "mm")),
breaks=seq(0, 1, 0.1),
limits = c(0, 1)) +
ggplot2::guides(color='none')
Finally, I called ggplotly as follows
plotly::ggplotly(plot)
When I produce the plot without interactivity, I get the following heatmap:
However, when I add interactivity, I get this:
I'm not sure what the issue is, but I suspect it may have something to do with the scale_fill_gradientn
and scale_color_gradientn
functions. However, as this is part of a bigger function, I need to specify the colors this way (and it works for non-interactive plots).
I described above what I tried and provided pictures of what I expected vs what I got.