Search code examples
pythonnumpymatplotlibpython-imaging-librarydrawing

How to mask a part of a line in matplotlib


I draw some lines with matplotlib in python :

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

fig_axes = (-100, 100, -50, 80)
x_range = (-800, 800, 33)
orig = (0,5)
x = np.linspace(x_range[0], x_range[1], x_range[2])

fig = plt.figure(figsize=(15, 9))

ax = fig.add_subplot(1,1,1)
ax.set_facecolor('black')
ax.axis([fig_axes[0], fig_axes[1], fig_axes[2], fig_axes[3]])


for i in x:
    ax.plot((orig[0], i), (orig[1], fig_axes[2]), 'r', linewidth=1.5)

plt.show()

Then i get an image like this :

output

Now I want to hide all the part above 0 on the graphic. I heard about

numpy.ma.masked_where

but I haven't an array, so i can't use it.

Did you have any idea how I can do it ?

I want something like that :

excepted output

Thanks


Solution

  • draw a rectangle to cover up

    import matplotlib.patches as patches
    rect = patches.Rectangle((-100,0),200,80,facecolor='black',fill=True,zorder=20)
    ax.add_patch(rect)
    

    or recalculate the ending points, should be basic geometry