matplotlibstacked-chartstacked-area-chartarea-chart

Matplotlib's stackplot change colors for overlapping regions


When I draw a stacked area plot using Matplotlib's stackplot, if a set of y values has a negative number in it, then that area will overlap with the area underneath. For example:

import matplotlib.pyplot as plt
plt.stackplot([1,2,3], [1,2,3], [1,0,-1])
plt.show()

stackplot

You can see the top set of y values are in orange. Since the right most y value is -1, it overlaps with the blue region. This is fine for my purposes. Except, I need that to be clear it's an overlap as opposed to the blue region just stayed at y=2.0 from x=2.0 to x=3.0 and the orange area is positive. Can overlaps like this be set to a different color?


Solution

  • Can overlaps like this be set to a different color?

    Yes, you could draw the second y data in two runs:

    import matplotlib.pyplot as plt
    import numpy as np
    
    y1 = [1,2,3]
    y2 = [1,0,-1]
    polys = plt.stackplot([1,2,3], y1, np.maximum(y2, 0), np.minimum(y2, 0))
    

    enter image description here

    I think, however, a better solution would be to make the colors semi-transpartent, maybe with additional hatching:

    polys = plt.stackplot([1,2,3], [1,2,3], [1,0,-1], alpha=0.3)
    for poly, hatch in zip(polys, ['|', '-']):
        poly.set_hatch(hatch)
        poly.set_edgecolor(poly.get_facecolor())
    

    enter image description here