Creating a plotly express image with custom image ratio

Viewed 93

I'm trying to build a very simple plot in plotly express with custom dimensions but cannot get the result I want.

My image is an array with dimensions 300 and 5000, I want it to be stretched into a smaller dimension, such that it looks big on a screen.

It is super easy to do in matplotlib, but I get weird results in plotly. This is what I have using matplotlib:

plt.figure(figsize=(20, 10), dpi=80)
image = np.random.random([300, 5000])
plt.imshow(image, vmin=0, vmax=1, cmap='gray_r', aspect='auto')

plot created by matplotlib

1 Answers

If I understand correctly, this is what you currently have:

# Missing imports
import matplotlib.pyplot as plt
import numpy as np

# Your code from the question
plt.figure(figsize=(20, 10), dpi=80)
# Smaller array to speed things up
image = np.random.random([30, 500])
plt.imshow(image, vmin=0, vmax=1, cmap="gray_r", aspect="auto")

This results in the following output:

enter image description here

Now you want to use plotly. You can plot the same image with the default settings:

# Plotly default
import plotly.express as px
fig = px.imshow(image)
fig.show()

Resulting in:

enter image description here

To get the same colour and aspect ratio you need to add some arguments to px.imshow. Note that here the width and height are in pixels, so you need to convert your (20, 10) numbers accordingly using the dpi of 80.

# Plotly to match matplotlib
fig = px.imshow(image, color_continuous_scale="gray_r", aspect="auto", width=1600, height=800)
fig.show()

This results in:

enter image description here

Related