cssrimageshinyantialiasing

How to suppress antialiasing of an image in shiny?


I have an image graphics in a shiny app with a relative large number of grid cells. However, smooth color transitions appear distorted in the browser. I suspect that this is an antialiasing artifact and wonder how it can be prevented, either in R or with a css option.

Here a minimal example in plain R, that looks smooth as expected:

library(RColorBrewer)
mycol <- colorRampPalette(brewer.pal(11, 'Spectral'))

png("image.png", width=600, height=600)
x <- seq(-0.5, 0.5, length.out = 200)
r <- sqrt(outer(x^2, x^2, `+`))
image(z = cos(r^2) * exp(-r/6), col = mycol(100))
dev.off()

picture with smooth colors

And the corresponding shiny demo, where the resulting image shows an annoying grid artifact:

library(shiny)
library(RColorBrewer)

mycol <- colorRampPalette(brewer.pal(11, 'Spectral'))

ui <- fluidPage(
    plotOutput("imagePlot")
)

server <- function(input, output) {
    output$imagePlot <- renderPlot({
        x <- seq(-0.5, 0.5, length.out = 200)
        r <- sqrt(outer(x^2, x^2, `+`))
        image(z = cos(r^2) * exp(-r/6), col = mycol(100))
    })
}

shinyApp(ui = ui, server = server)

image with distorted colors


Solution

  • Very better with the parameter useRaster = TRUE:

    server <- function(input, output) {
      output$imagePlot <- renderPlot({
        x <- seq(-0.5, 0.5, length.out = 200)
        r <- sqrt(outer(x^2, x^2, `+`))
        image(z = cos(r^2) * exp(-r/6), col = mycol(100), useRaster = TRUE)
      })
    }
    

    enter image description here