Rami
Rami

Reputation: 381

Altair - Area chart fill bleeds out from chart

I'm using the altair library to build a graph, however for some reason the area fill bleeds out of the chart.

Here is the code

import altair as alt

# Determine the minimum and maximum values for the y-axis
y_min = price_data["close"].min()
y_max = price_data["close"].max()

# Create the chart with adjusted y-axis
alt.Chart(price_data).mark_area(
    line={'color': 'darkgreen'},
    color=alt.Gradient(
        gradient='linear',
        stops=[alt.GradientStop(color='white', offset=0),
               alt.GradientStop(color='darkgreen', offset=1)],
        x1=1,
        x2=1,
        y1=1,
        y2=0
    )
).encode(
    alt.X('date:T', title="Date"),
    alt.Y('close:Q', scale=alt.Scale(domain=[y_min, y_max]), title="Close Price")
).properties(
    title=f"{symbol} Price Trend"
)

I suspect it's something to do with the y_min and y_max.

Here is the image yielded: Image showing the graph's filling bleeding out

I tried to create an area chart with gradient fill from green to white.

Upvotes: 0

Views: 49

Answers (1)

dnelson17
dnelson17

Reputation: 89

You're just missing the clip parameter in the Chart.mark_area method. From the Altair docs, this parameter determines "Whether a mark be clipped to the enclosing group's width and height".

So, all you need to do is add the following line (don't forget a comma at the end of the line above!):

alt.Chart(price_data).mark_area(
    line={'color': 'darkgreen'},
    color=alt.Gradient(
        gradient='linear',
        stops=[alt.GradientStop(color='white', offset=0),
               alt.GradientStop(color='darkgreen', offset=1)],
        x1=1,
        x2=1,
        y1=1,
        y2=0
    ),
    clip=True, # add this line
).encode(
    alt.X('date:T', title="Date"),
    alt.Y('close:Q', scale=alt.Scale(domain=[y_min, y_max]), title="Close Price")
).properties(
    title=f"{symbol} Price Trend"
)

Chart differences

For the dataset I had, here is the before chart:

Before chart

And the after chart:

Chart with clip=True applied

Upvotes: 0

Related Questions