在绘图上绘制带阴影的矩形

时间:2013-11-18 16:06:38

标签: python matplotlib shadow rectangles

目前,要在matplotlib的情节上绘制一个矩形,我使用:

currentAxis = plt.gca()
rect = mpatch.Rectangle((0.2, 0.420), 5.65, 0.730, edgecolor = None, facecolor = "white", zorder = 3)
currentAxis.add_patch(rect)

如何为这个矩形添加阴影(比如传说)?

2 个答案:

答案 0 :(得分:2)

一旦这样做,就是使用transformations。以下是使用scale translation方法尝试提供(我相信!)您所要求的内容的示例:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.transforms as transforms

# set up fig and axis
fig = plt.figure()
currentAxis = plt.gca()

# set translation 
dx, dy = 5/72., -5/72.
offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
shadow_transform = currentAxis.transData + offset

# plot patch shadow
rect = patches.Rectangle((0.2, 0.420), 0.65, 0.730, transform=shadow_transform, 
                         edgecolor = None, facecolor = "black", zorder = 3)
currentAxis.add_patch(rect)

# plot patch
rect = patches.Rectangle((0.2, 0.420), 0.65, 0.730, edgecolor = None, 
                         facecolor = "white", zorder = 3)
currentAxis.add_patch(rect)

请注意传递给transform方法的Rectangle参数。

输出:

shadowing

答案 1 :(得分:0)

您现在可以在matplotlib中使用内置的shadow

rect = matplotlib.patches.Rectangle((0.4, 0.2), 0.4, 0.35, 
                                    facecolor='white', edgecolor='gray',
                                    transform=ax.transAxes)
shadow = matplotlib.patches.Shadow(rect, 1/72., -1/72)                                        
ax.add_patch(shadow)
ax.add_patch(rect)