Xeno6x
Xeno6x

Reputation: 85

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

Upvotes: 0

Views: 1015

Answers (3)

Xeno6x
Xeno6x

Reputation: 85

So, like as requested in the comment, i draw a rectangle on it with :

ax.add_patch(ptc.Rectangle((fig_axes[0], 0), (fig_axes[1]-fig_axes[0]), (orig[1]+5), fc ='black', zorder = 3))

Upvotes: 0

Stef
Stef

Reputation: 30579

You can set a rectangle clip path on the lines:

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

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]])

r = mp.Rectangle((fig_axes[0],fig_axes[2]), fig_axes[1]-fig_axes[0], 0-fig_axes[2], transform=ax.transData)
for i in x:
    l = ax.plot((orig[0], i), (orig[1], fig_axes[2]), 'r', linewidth=1.5)
    l[0].set_clip_path(r)

Upvotes: 3

Bing Wang
Bing Wang

Reputation: 1598

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

Upvotes: 3

Related Questions