[Python] I want to fill the gaps in PyPlot fill_betweenx calls

Discussão em 'Python' iniciado por Stack, Março 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to use Python to plot some data using pyplot.fill_betweenx.

    Here is an example of code without considering category:

    import numpy as np
    import matplotlib.pyplot as plt

    category = np.array(['A','A','A','B','B','B','C','C','C'])
    elev = np.array([100,90,80,70,60,50,40,30,20])
    strength = np.array([8,8,7,6,6,6,9,10,10])

    plt.fill_betweenx(elev,strength,step='mid')
    plt.show()


    I want to color the plot based on the category at the same index but am having issues with gaps.

    No category image

    [​IMG]

    I tried this approach:

    plt.fill_betweenx(elev,np.where(category == 'A',strength,np.nan),step='mid',color='firebrick')
    plt.fill_betweenx(elev,np.where(category == 'B',strength,np.nan),step='mid',color='royalblue')
    plt.fill_betweenx(elev,np.where(category == 'C',strength,np.nan),step='mid',color='seagreen')
    plt.show()


    However, it results in gaps where the category changes.

    Gaps!

    [​IMG]

    I understand why there are gaps but I am having trouble coming up with a solution to it. Ideally, I'd like to fill the gap with the color of the category before it such that it results in something like the image below:

    No gaps!

    [​IMG]

    Any suggestions? Thanks!

    Continue reading...

Compartilhe esta Página