'Creating a Graph with Python in Jupyter Notebook Using Altair and I Cannot Move the legend for the Color

bars = alt.Chart(marvel).mark_bar().encode(
    x=alt.X('OpeningWeekendNorthAmerica', axis=alt.Axis(title='Gross Revenue Opening Weekend')),
    y=alt.Y('Title', axis=alt.Axis(title='Movie Title')),
    color="Budget"
)

text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='Distributor'
)



(bars + text).properties(height=900)

I Just want to know how to move the color key from the upper right to the middle right side of the graph to avoid the text overlapping. Link to Chart Image



Solution 1:[1]

You can use the orient and offset legend properties to control the location of the legend (see https://altair-viz.github.io/user_guide/generated/core/altair.Legend.html)

For example, here is a legend located at the bottom left:

import altair as alt
from vega_datasets import data

alt.Chart(data.cars()).mark_circle(size=60).encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color=alt.Color('Origin', legend=alt.Legend(orient='bottom-left'))
)

enter image description here

For even more control, you can set orient='none' and use the legendX and legendY configurations to specify the position relative to the top left corner of the chart:

alt.Chart(data.cars()).mark_circle(size=60).encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color=alt.Color('Origin', legend=alt.Legend(orient='none', legendX=410, legendY=110))
)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jakevdp