pythonseabornseaborn-objects

Dual y-axis plot using seaborn objects (v0.12)


I am trying to make a dual y-axis plot using the new seaborn interface (seaborn.objects, available in v0.12). However, I am having difficulties getting it to work.

My first try is this:

import seaborn.objects as so

df = pd.DataFrame(
    {"x": [1, 2, 3, 4, 5], "y1": [5, 2, 1, 6, 2], "y2": [100, 240, 130, 570, 120]}
)
fig, ax1 = plt.subplots(1, 1, figsize=(10, 5))
ax2 = ax1.twinx()
so.Plot(df, x="x").add(so.Bar(), y="y1", ax=ax1).add(so.Line(), y="y2", ax=ax2)

But this will create the seaborn plot with one y-axis and an empty dual-axis plot.


Solution

  • You'll want to call Plot.on to use pre-existing matplotlib axes:

    import seaborn.objects as so
    
    df = pd.DataFrame(
        {"x": [1, 2, 3, 4, 5], "y1": [5, 2, 1, 6, 2], "y2": [100, 240, 130, 570, 120]}
    )
    fig, ax1 = plt.subplots(1, 1, figsize=(10, 5))
    ax2 = ax1.twinx()
    p = so.Plot(df, x="x")
    p.add(so.Bar(), y="y1").on(ax1).plot()
    p.add(so.Line(), y="y2").on(ax2).plot()
    

    enter image description here

    Note that there will likely be a Plot.twin method to make this more natural, but it's not been implemented yet.