frits frits - 4 months ago 21
Python Question

combining patches to obtain single transparency in matplotlib

I calculate ellipse-like polygons which are drawn over another image. The polygons together form one shape and must have a single transparency. Unfortunately, if I draw one polygon after another, the stack gets different transparencies. In the example below I have 3 polygons, creating 3 transparencies, resulting in different grey areas instead of one. Does anyone know how to obtain a single transparency?

Thank you

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon, Rectangle

def get_ellipse_coords(a=0.0, b=0.0, x=0.0, y=0.0, angle=0.0, k=2):

pts = np.zeros((360*k+1, 2))
beta = -angle * np.pi/180.0
sin_beta = np.sin(beta)
cos_beta = np.cos(beta)
alpha = np.radians(np.r_[0.:360.:1j*(360*k+1)])

sin_alpha = np.sin(alpha)
cos_alpha = np.cos(alpha)

pts[:, 0] = x + (a * cos_alpha * cos_beta - b * sin_alpha * sin_beta)
pts[:, 1] = y + (a * cos_alpha * sin_beta + b * sin_alpha * cos_beta)

return pts

if __name__ == '__main__':

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
plt.xlim([-5,5])
plt.ylim([-5,5])

c='0.5'
alp=0.5

ax.add_patch(Rectangle((1.5, -4.0),0.5,8.0,
color='lightblue', zorder=1))

pts = get_ellipse_coords(a=4.0, b=1.0)
ax.add_patch(Polygon(pts, closed=True, lw=0.5,
color=c, alpha=alp,zorder=2))

pts = get_ellipse_coords(a=4.0, b=1.0, x=1.0, angle=30)
ax.add_patch(Polygon(pts, closed=True, lw=0.5,
color=c, alpha=alp, zorder=2))

pts = get_ellipse_coords(a=2.0, b=0.25, x=2.0, y=-2.0, angle=250)
ax.add_patch(Polygon(pts, closed=True, lw=0.5,
color=c, alpha=alp, zorder=2))

plt.show()


np.concatenate, suggested in the first answer, does the trick I need:

[...]
ax.add_patch(Rectangle((1.5, -4.0),0.5,8.0,
color='lightblue', zorder=1))

pts1 = get_ellipse_coords(a=4.0, b=1.0)
pts2 = get_ellipse_coords(a=4.0, b=1.0, x=1.0, angle=30)
pts3 = get_ellipse_coords(a=2.0, b=0.25, x=2.0, y=-2.0, angle=250)

stoppoint = np.array([[np.nan,np.nan]])
pts = np.concatenate((pts1, stoppoint, pts2))
pts = np.concatenate((pts, stoppoint, pts3))

ax.add_patch(Polygon(pts, closed=True, lw=0.0,
color=c, alpha=alp, zorder=2))

Answer

Like this:

pts1 = get_ellipse_coords(a=4.0, b=1.0)
pts2 = get_ellipse_coords(a=4.0, b=1.0, x=1.0, angle=30)
stoppoint = np.array([[nan,nan]])     

pts = np.concatenate((pts1, stoppoint, pts2))

ax.add_patch(Polygon(pts, closed=True, lw=0.5,
                     color=c, alpha=alp,zorder=2))

The stoppoint prevents a line connecting the ellipses.

Comments