在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')
...但是Axes对象没有'edgecolor'这个属性,我也找不到从图形层面给图加边框的方法。
其实我是在封装mpl代码,并添加一个wx界面,想根据选中的子图来更新控件。也就是说,用户点击图形画布中的子图——这个子图就被“选中”(周围有个边框,最好是锯齿状的)——然后界面更新,显示可以修改这个特定子图的控件。
2 个回答
11
另一种解决方案是来自于这个StackOverflow上的回答,它讲的是如何将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()
结果:
16
你基本上是想在坐标轴外面画东西,对吧?
我从这里改编了这个内容。里面有一些硬编码的“调整因子”,需要整理一下。
#!/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')
生成的效果是: