Search code examples
pythonimageplotlylabelsubplot

How to add titles to subplots containing images


Starting from a basic image example, I made 3 subplots:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

imgs_rgb = (
    [[[255, 0, 0], [0, 255, 0], [0, 0, 255]],
     [[0, 255, 0], [0, 0, 255], [255, 0, 0]]],
    [[[255, 127, 0], [127, 255, 0], [127, 0, 255]],
     [[127, 255, 0], [127, 0, 255], [255, 127, 0]]],
    [[[0, 255, 255], [0, 255, 127], [255, 0, 255]],
     [[255, 255, 0], [0, 255, 255], [127, 255, 0]]],
)    

fig = make_subplots(rows=len(imgs_rgb), cols=1)
for row, img_rgb in enumerate(imgs_rgb):
    fig.add_trace(
        go.Image(z=img_rgb),
        row=row+1,
        col=1
    )

fig.show()

How can we add a title/label to each individual subplot, as shown e.g here: https://plotly.com/python/imshow/#exploring-3d-images-timeseries-and-sequences-of-images-with-facetcol

image showing 3 images with different titles

Note that I don't have plotly.express, so using its functionality isn't an option.


Solution

  • You can just a pass the subplot titles when calling make_subplots():

    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    imgs_rgb = (
        [[[255, 0, 0], [0, 255, 0], [0, 0, 255]],
         [[0, 255, 0], [0, 0, 255], [255, 0, 0]]],
        [[[255, 127, 0], [127, 255, 0], [127, 0, 255]],
         [[127, 255, 0], [127, 0, 255], [255, 127, 0]]],
        [[[0, 255, 255], [0, 255, 127], [255, 0, 255]],
         [[255, 255, 0], [0, 255, 255], [127, 255, 0]]],
    )    
    
    fig = make_subplots(rows=len(imgs_rgb), cols=1, subplot_titles=("Plot1", "Plot2", "Plot3"))
    for row, img_rgb in enumerate(imgs_rgb):
        fig.add_trace(
            go.Image(z=img_rgb),
            row=row+1,
            col=1
        )
    
    fig.show()
    

    enter image description here