plotly.R icon indicating copy to clipboard operation
plotly.R copied to clipboard

Bug: ggplotly ignores colours in ggplot2::scale_fill_gradientn when limits are below the range of the data

Open talgalili opened this issue 9 years ago • 2 comments

This is an odd bug (reported first as a heatmaply issue).

If we create a ggplot2 object with colors based on scale_fill_gradientn, then ggplotly respect the colors. But if the limits are set to be within (instead of outside) the range of the data, then ggplotly stops respecting the colors. This may be some fallback for how to deal with NA colors (but I don't know enough about ggplotly to know for sure).

Here is a self contained example:


library(ggplot2)
library(viridis)
library(plotly)
# Equivalent fill scales do the same job for the fill aesthetic
p <- ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density)) +
  scale_fill_gradientn(colours = viridis(10), limits = c(0.001,.01))
p
ggplotly(p)

Plot in ggplot2: image

Plot in plotly (see the wrong colors produced!) image

talgalili avatar May 26 '16 07:05 talgalili

Possibly related to #907

cpsievert avatar Apr 06 '17 22:04 cpsievert

Finally, I found a solution ! I had a similar problem, so I hope it can help anyone going back to this bug : the scale_fill_gradient can't handle values that are out of the limits that you fix (here your density range goes from 0 to 0.36 , but you want a gradient starting from 0.001 and finishing at 0.1 : the out-of-range values produce NAs so it puts it as gray in ggplot) So the solution is to use squish from the scales package :

library(scales) scale_fill_gradient(low = "red", high = "green", limits=c(0.6, 1), oob=squish)

So both ggplot and the plotly figures work as intended

image

Mr-Laurent avatar Aug 17 '22 14:08 Mr-Laurent

I have come the same issue when using scale_fill_gradient2 with ggplotly. With ggplot, the colors are correctly allocated but ggplotly doesn't render them correctly. oob=squish didn't solve it for me, unfortunately. Funny thing is that scale_color_gradient2 works perfectly even with ggplotly ... so the issue seems to be specifically the 'fill' aes . Just found this highly related issue https://github.com/plotly/plotly.R/issues/1234

rocanja avatar Feb 09 '23 02:02 rocanja