Skip to content

Combined Stacked Barplot & Streamgraph

Ilia Popov edited this page Jul 17, 2025 · 3 revisions

Stacked Barplot and Streamgraph can be combined to provide the most comprehensive view on relative abundance across samples possible.

Step 1: Create Stacked Barplot

Detailed instructions can be found at Stacked Barplot API page

df = pd.read_csv("demo_data/counts/csv_relabund/counts_species_2.csv")

kpstbar = kp.stacked_barplot(
    df,
    figsize=(12, 6),
    bar_width = 0.6,
    edge_linewidth = 0.6,
    cmap="tab20",
    xticks_fontsize=12,
    # To create combined figure it is VERY important to use `None` background_color
    background_color=None
    )

# Save the figure using `transparent=True`
kpstbar.savefig("kpstbar.png", transparent=True)
kpstbar.plotfig()

Sample output:

kpstbar

Step 2: Create Streamgraph

Detailed instructions can be found at Streamgraph API page

df = pd.read_csv("demo_data/counts/csv_relabund/counts_species_2.csv")

kpstream = kp.streamgraph(
    df,
    figsize=(12, 6),
    # To create combined figure it is VERY important adjust fill_alpha
    fill_alpha=0.2,
    edgecolor="black",
    edge_linewidth = 0.6,
    cmap="tab20",
    xticks_fontsize=12,
    # To create combined figure it is VERY important to use `None` background_color
    background_color=None
    )

# Save the figure using `transparent=True`
kpstream.savefig("kpstream.png", transparent=True)
kpstream.plotfig()

Sample output:

kpstream_alpha

Step 3: Create combined figure

With transparent background

from PIL import Image

# Load both images as RGBA
bottom = Image.open("kpstream.png").convert("RGBA")
top    = Image.open("kpstbar.png").convert("RGBA")

# Paste the top image over the bottom using its own alpha channel
bottom.paste(top, (0, 0), top)

# Save &/or show
bottom.save("combined.png")
bottom.show()

Sample output:

combined

With white background

from PIL import Image

# Load both images as RGBA
bottom = Image.open("kpstream.png").convert("RGBA")
top    = Image.open("kpstbar.png").convert("RGBA")

# Paste the top image over the bottom using its own alpha channel
bottom.paste(top, (0, 0), top)

# Now flatten onto a white background
white_bg = Image.new("RGB", bottom.size, (255, 255, 255))
# Use alpha as mask
white_bg.paste(bottom, mask=bottom.split()[3])  

# Save &/or show
white_bg.save("combined_white.png")
white_bg.show()

Sample output:

combined_white

Clone this wiki locally