vega / altair

Declarative statistical visualization library for Python
https://altair-viz.github.io/
BSD 3-Clause "New" or "Revised" License
9.25k stars 789 forks source link

docs: bar chart with labels coloured by measured luminance #3614

Closed mattijn closed 2 days ago

mattijn commented 3 days ago

This PR adds an example that demonstrates how to change the color of text labels based on measured luminance.

The example looks as such:

image

Usage of luminance for the text color of the labels was created using the following code (method-based syntax):

import altair as alt
from vega_datasets import data

source = data.barley()

base = alt.Chart(source).encode(
    x=alt.X('sum(yield):Q').stack('zero'),
    y=alt.Y('site:O').sort('-x'),
    text=alt.Text('sum(yield):Q', format='.0f')
)

bars = base.mark_bar(
    tooltip=alt.expr("luminance(scale('color', datum.sum_yield))")
).encode(
    color='sum(yield):Q'
)

text = base.mark_text(
    align='right',
    dx=-3,
    color=alt.expr("luminance(scale('color', datum.sum_yield)) > 0.5 ? 'black' : 'white'")
)

bars + text

Especially this line

color=alt.expr("luminance(scale('color', datum.sum_yield)) > 0.5 ? 'black' : 'white'")

In the expression above this is written as a predicate. The text appears black if the luminance is above 0.5 and white when the luminance is below 0.5. The luminance is computed using the color scale in combination with the internal computed data field datum.sum_yield. Inspecting the luminance can be done through the tooltip by hovering the bars.

Currently this expression is a str with plain Vega Expression syntax. It would be nice to use the equivalent python syntax instead.

joelostblom commented 3 days ago

Love this example! I have been doing similar things with a manual threshold as I didn't know there was a function in Vega to compute the luminance already!