fig.add_subplot() *transform* 不起作用? [英] fig.add_subplot() *transform* doesn't work?

查看:53
本文介绍了fig.add_subplot() *transform* 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于帖子 在 matplotlib 的子图中嵌入小图,我正在研究此解决方案,但是由于某些原因,转换被忽略了!

Regarding to the post Embedding small plots inside subplots in matplotlib, I'm working on this solution, but for some reason, transform is ignored!

我错了吗?还是有错误?

I'm in a mistake? Or there is a bug?

import matplotlib.pyplot as plt
import numpy as np

axes = []
x = np.linspace(-np.pi,np.pi)
fig = plt.figure(figsize=(10,10))
subpos = (0,0.6)

for i in range(4):
   axes.append(fig.add_subplot(2,2,i))

for axis in axes:
    axis.set_xlim(-np.pi,np.pi)
    axis.set_ylim(-1,3)
    axis.plot(x,np.sin(x))
    fig.add_axes([0.5,0.5,0.1,0.1],transform=axis.transAxes)

plt.show()

推荐答案

import matplotlib.pyplot as plt
import numpy as np

def axis_to_fig(axis):
    fig = axis.figure
    def transform(coord):
        return fig.transFigure.inverted().transform(
            axis.transAxes.transform(coord))
    return transform

def add_sub_axes(axis, rect):
    fig = axis.figure
    left, bottom, width, height = rect
    trans = axis_to_fig(axis)
    figleft, figbottom = trans((left, bottom))
    figwidth, figheight = trans([width,height]) - trans([0,0])
    return fig.add_axes([figleft, figbottom, figwidth, figheight])

x = np.linspace(-np.pi,np.pi)
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10,10))

for axis in axes.ravel():
    axis.set_xlim(-np.pi, np.pi)
    axis.set_ylim(-1, 3)
    axis.plot(x, np.sin(x))
    subaxis = add_sub_axes(axis, [0.2, 0.6, 0.3, 0.3])
    subaxis.plot(x, np.cos(x))

plt.show()

收益

这篇关于fig.add_subplot() *transform* 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆