Bebio
Bebio

Reputation: 409

Python altair - facet line plot with multiple variables

I have the following kind of DataFrame

Marque Annee Modele PVFP           PM
0   A   1   Python  70783.066836    2.067821e+07
1   A   2   Python  75504.270716    1.957717e+07
2   A   3   Python  66383.237169    1.848982e+07
3   A   4   Python  61966.851675    1.755261e+07
4   A   5   Python  54516.367597    1.671907e+07
5   A   1   Sol     66400.686091    2.067821e+07
6   A   2   Sol     74953.770294    1.955218e+07
7   A   3   Sol     66500.916446    1.844078e+07
8   A   4   Sol     62016.941237    1.748098e+07
9   A   5   Sol     54356.008414    1.662684e+07
10  B   1   Python  43152.461787    1.340989e+07
11  B   2   Python  62397.794144    1.494418e+07
12  B   3   Python  1871.135251     2.178552e+06

I tried to build a facet graph but without really succeeding. I'am just able to concat vertically the 2 charts generated. I would be grateful if you have any idea to do it properly in one operation.

My current code :

   chart = alt.Chart(euro).mark_line().encode(
    x='Annee',
    y='PVFP',
    color='Modele'
).properties(
    width=150,
    height=150
).facet(
    facet='Marque',
    columns=3
)

chart2 = alt.Chart(euro).mark_line().encode(
    x='Annee',
    y='PM',
    color='Modele'
).properties(
    width=150,
    height=150
).facet(
    facet='Marque',
    columns=3
)

chart & chart2

enter image description here

Upvotes: 1

Views: 2117

Answers (1)

jakevdp
jakevdp

Reputation: 86310

One good way to do this is to use a Fold Transform to fold your two columns into one, and then you can use row and column facets to facet by both variables at once. For example:

alt.Chart(euro).transform_fold(
    ['PVFP', 'PM'], as_=['key', 'value']
).mark_line().encode(
    x='Annee:Q',
    y='value:Q',
    color='Modele:N'
).properties(
    width=150,
    height=150
).facet(
    column='Marque:N',
    row='key:N'
)

Upvotes: 1

Related Questions