Search code examples
plotly

how to disable interpolation in plotly?


I have something like following:

    fig.add_layout_image(
        dict(
            source=prefix_webp + base64.b64encode(webp_data).decode("utf-8"),
            xref='x', yref='y',  # Reference subplot axes
            x=0, y= 1,  # Position in subplot grid
            sizex=1, sizey=1,
            xanchor='left', yanchor='top',
            sizing='contain',  # Ensure it fits within the given size
        ),
        row=row, col=col
    )

Sine the image has small amount of pixels. If I save the figure as PDF, the image is pixelated which is what I wanted, because it is actually represent some data, I would like to see the exact edge of each pixel.

However, if I display it in browser or save it as html. The image seems interpolated and becomes smooth.

I wonder how can I disable this in plotly

try to add the css via template does not really work

html_template = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plotly Layout Image Example</title>
    <style>
        /* Custom CSS to apply pixelated rendering to images */
        img {
            image-rendering: pixelated;
        }
    </style>
</head>
<body>

    <h1>Plotly Layout Image Example</h1>
    <!-- This is where the Plotly figure will be inserted -->
    {{ fig | safe }}

</body>
</html>
'''

plotly_html = fig.to_html(full_html=False)

from jinja2 import Template
template = Template(html_template)
html_output = template.render(fig=plotly_html)
with open(os.path.expanduser('test-css.html'), 'w') as file:
    file.write(html_output)

Solution

  • finally it works. We need to identify the image tag as svg image.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Plotly Layout Image Example</title>
        <style>
            /* Custom CSS to apply pixelated rendering to images */
            svg image {
                image-rendering: pixelated;
            }
        </style>
    </head>
    <body>
    
        <h1>Plotly Layout Image Example</h1>
        <!-- This is where the Plotly figure will be inserted -->
        {{ fig | safe }}
    
    </body>
    </html>
    

    This template finally works