Add image to graph footer in Altair

Viewed 443

Is there a way to add a logo or image, for example, on the footer of an Altair plot? Like this example image (https://i.imgur.com/zHqeoHB.png) on the following graph:

import altair as alt

from vega_datasets import data
cars = data.cars()

one = alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin',
).properties(
    title = "Miles per gallon and Horsepower",
    width = 300,
    height = 300
)

alt.concat(one).properties(
    title=alt.TitleParams(
        ['Source: blablabla.', '@jballesterosc_'],
        baseline='bottom',
        orient='bottom',
        anchor='end',
        fontWeight='normal',
        fontSize=10
    )
)

enter image description here

1 Answers

You can do this by using a Layer Chart with an Image Mark. For example:

import altair as alt
from vega_datasets import data
cars = data.cars()

one = alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin',
).properties(
    title = "Miles per gallon and Horsepower",
    width = 300,
    height = 300
)

img = alt.Chart({
    "values": [{"url": "https://i.imgur.com/zHqeoHB.png"}]
}).mark_image(opacity=0.5).encode(
    x=alt.value(270), x2=alt.value(300),  # pixels from left
    y=alt.value(320), y2=alt.value(350),  # pixels from top
    url="url:N"
)

alt.layer(one, img)

enter image description here

notice that the x, x2, y, and y2 encodings here are specified as pixel values, and control the horizontal and vertical extent of the image. By setting them to values larger than the specified chart bounds, the image will appear outside the chart axis.

Related