在matplotlib中绘制子图周围的边框

Ada*_*ser 14 python matplotlib

任何人都知道如何在matplotlib中的图形中围绕单个子图绘制边框?我正在使用pyplot.

例如:

import matplotlib.pyplot as plt
f = plt.figure()
ax1 = f.add_subplot(211)
ax2 = f.add_subplot(212)
# ax1.set_edgecolor('black')
Run Code Online (Sandbox Code Playgroud)

..但Axes对象没有'edgecolor',我似乎无法找到从图形级别勾画出情节的方法.

我实际上是在包装mpl代码并添加带有控件的wx UI,我想根据选择的子图来获取上下文.即,用户点击图画布中的子图 - 子图是"已选中"(在其周围绘制轮廓,理想情况下是锯齿) - GUI更新以呈现控件以修改该特定子图.

Mar*_*ark 13

你基本上想要在轴外绘制,对吧?

我从这里改编了这个.它需要清理,因为我在那里使用了一些硬编码的"软糖因子".

#!/usr/bin/env python
from pylab import *

def f(t):
    s1 = cos(2*pi*t)
    e1 = exp(-t)
    return multiply(s1,e1)

t1 = arange(0.0, 5.0, 0.1)
t2 = arange(0.0, 5.0, 0.02)
t3 = arange(0.0, 2.0, 0.01)

figure(figsize=(4, 4))
sub1 = subplot(211)
l = plot(t1, f(t1), 'bo', t2, f(t2), 'k--', markerfacecolor='green')
grid(True)
title('A tale of 2 subplots')
ylabel('Damped oscillation')

## I ADDED THIS
autoAxis = sub1.axis()
rec = Rectangle((autoAxis[0]-0.7,autoAxis[2]-0.2),(autoAxis[1]-autoAxis[0])+1,(autoAxis[3]-autoAxis[2])+0.4,fill=False,lw=2)
rec = sub1.add_patch(rec)
rec.set_clip_on(False)

subplot(212)
plot(t3, cos(2*pi*t3), 'r.')
grid(True)
xlabel('time (s)')
ylabel('Undamped')

savefig('test.png')
Run Code Online (Sandbox Code Playgroud)

生产:

在此输入图像描述


MPA*_*MPA 6

关于将补丁直接放置到图形画布而不是单个轴的SO 上的这个答案衍生出另一种解决方案Rectangle

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=2, ncols=1)
axes[0].plot(np.cumsum(np.random.randn(100)))
axes[1].plot(np.cumsum(np.random.randn(100)))

rect = plt.Rectangle(
    # (lower-left corner), width, height
    (0.02, 0.5), 0.97, 0.49, fill=False, color="k", lw=2, 
    zorder=1000, transform=fig.transFigure, figure=fig
)
fig.patches.extend([rect])

plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明