Search code examples
altair

Pie Chart with Labels and facet in altair: not able to proper render the value labels


Using the single chart example, I have a label for each piece of cake.

enter image description here

If I try to transform it in a faceted chart using this code

df=pd.read_csv("input.csv",keep_default_na=False)

base=alt.Chart(df).encode(
    theta=alt.Theta(field="v", type="quantitative"),
    color=alt.Color(field="k", type="nominal")
)


pie = base.mark_arc(outerRadius=100)
text = base.mark_text(radius=115,fill= "black").encode(alt.Text(field="v", type="quantitative", format=",.1f"))

alt.layer(pie, text, data=df).facet(column='label')

all the labels are all in the same wedge and then illegible (here the vega lite version vega lite version).

enter image description here

how to have a result similar to that of the single chart?

Thank you

f,n,k,v,label
1,3,0-5 %,99.7289972899729,Forest
1,4,5-10 %,0.27100271002710025,Forest
0,1,0-5 %,100.0,Non-Forest
254,5,0-5 %,99.0077177508269,unclassifiable
254,6,5-10 %,0.9922822491730982,unclassifiable

Solution

  • I must add:

    • stack=True as channel encoding option in the theta channel encoding;
    • and .resolve_scale( theta="independent" ) to the chart.

    And it works (I learned this thanks to Mattijn van Hoek).

    df=pd.read_csv("input.csv",keep_default_na=False)
    
    base=alt.Chart(df).encode(
        theta=alt.Theta(field="v", type="quantitative", stack=True),
        color=alt.Color(field="k", type="nominal")
    )
    
    
    pie = base.mark_arc(outerRadius=100)
    text = base.mark_text(radius=115,fill= "black").encode(alt.Text(field="v", type="quantitative", format=",.1f"))
    
    alt.layer(pie, text, data=df).facet(column='label').resolve_scale(theta="independent")