Search code examples
pythonpandasaltairgraph-visualization

Altair: showing the value of the current point in the tooltip


In the code below, we have a dataset that can be read as: "two cooks cook1, cook2 are doing a competition. They have to make four dishes, each time with two given ingredients ingredient1, ingredient2. A jury has scored the dishes and the grades are stored in _score.

I want to use Altair to show a graph where the x-axis is each dish (1, 2, 3, 4) and the y-axis contains the scores of the two cooks separately. This currently works but the main issue is that on hover, the tooltip does not include the score of the current point that is being hovered.

import altair as alt
import pandas as pd


df = pd.DataFrame({
    "ingredient1": ["potato", "onion", "carrot", "beet"],
    "ingredient2": ["tomato", "pepper", "zucchini", "lettuce"],
    "dish": [1, 2, 3, 4],
    "cook1": ["cook1 dish1", "cook1 dish2", "cook1 dish3", "cook1 dish4"],
    "cook1_score": [0.4, 0.3, 0.7, 0.9],
    "cook2": ["cook2 dish1", "cook2 dish2", "cook2 dish3", "cook2 dish4"],
    "cook2_score": [0.6, 0.2, 0.5, 0.6],
})


value_vars = [c for c in df.columns if c.endswith("_score")]
cook_names = [c.replace("_score", "") for c in value_vars]
id_vars = ["dish", "ingredient1", "ingredient2",] + cook_names
df_melt = df.melt(id_vars=id_vars, value_vars=value_vars,
                  var_name="cook", value_name="score")

chart = alt.Chart(df_melt).mark_circle().encode(
    x=alt.X("dish:O", title="Dish number"),
    y=alt.Y("score:Q", title="Score"),
    color="cook:N",
    tooltip=id_vars
)

chart.show()

I tried explicitly adding the score columns to the tooltip:

    tooltip=id_vars+value_vars

But that yields the following error:

ValueError: cook1_score encoding field is specified without a type; the type cannot be inferred because it does not match any column in the data.

So how can I get altair to also show the score of (only) the currently hovered element?


Solution

  • cook1_score is not a column in df_melt, which is why you see the error. Setting tooltip=id_vars+['score'] will work.