【问题标题】:fig.add_subplot() *transform* doesn't work?fig.add_subplot() *transform* 不起作用?
【发布时间】:2013-07-02 22:10:49
【问题描述】:

关于Embedding small plots inside subplots in matplotlib 的帖子,我正在研究这个解决方案,但由于某种原因,transform 被忽略了!

我错了?还是有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()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:
    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()
    

    产量

    【讨论】:

    • 主要问题是使用某种方法在子图中模拟 plt.axes() 。这个想法是在网格的每个子图中做小子图。看stackoverflow.com/questions/17458580/…
    • 好的,但这不是我的问题的答案...我知道如何使用与您类似的方法来做到这一点,但我不明白为什么 fig.add_axes 支持 transform karg () 并且不起作用。
    • transform kwarg -- 最多 -- 将 points 从一个坐标系转换到另一个坐标系。高度和宽度是比率,而不是点,因此无法使用 transform kwarg 单独将 [left, bottom, width, height] 列表从相对于轴的列表转换为相对于图形的适当列表.
    • 是的,但是在一个盒子里转换比率是微不足道的。所以,我不明白为什么变换是 add_axes 的卡格。无论如何,它很有用。谢谢。我有另一个帖子可以解决这个问题,与您的解决方案非常相似。 stackoverflow.com/questions/17458580/…
    猜你喜欢
    • 2014-09-01
    • 2012-05-17
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2021-02-08
    相关资源
    最近更新 更多