Skip to main content
 首页 » 编程设计

python之在 Matplotlib 中的极坐标图上设置 xlim、ylim

2024年10月24日12kerrycode

我在 matplotlib 中使用极坐标绘图来制作一组示意图,看起来像,

子图之间的空白比我想要的要多。在极坐标中,set_xlim 不起作用,set_ylim 设置半径限制。我可以调整 xlim 和 ylim 吗?减少子图之间空白的最佳方法是什么?


import matplotlib 
import matplotlib.pyplot as plt 
import numpy as np 
 
def schematic0(): 
    fig = plt.figure(figsize=(3., 3.)) 
    a_theta = np.linspace(-8, 8, 17) * np.pi / 8. 
    a = np.cos(0.5 * a_theta) 
    fig.subplots_adjust(left=0., bottom=0., right=1., top=1., 
                        wspace=0., hspace=0.) 
    for j in range(1, 5): 
        fig.add_subplot(2, 2, j, projection='polar') 
        ax = fig.gca() 
        ax.bar(a_theta, a, width=np.pi/8, color='w') 
        ax.spines['polar'].set_visible(False) 
        ax.set_xticklabels([]) 
        ax.set_yticklabels([]) 
        ax.xaxis.grid(False) 
        ax.yaxis.grid(False) 
    plt.savefig('foo0.png') 
    return fig 

我可以通过使用重叠的轴来使它看起来更像我想要的,

def schematic2(): 
    fig = plt.figure(figsize=(3., 3.)) 
    a_theta = np.linspace(-8, 8, 17) * np.pi / 8. 
    a = np.cos(0.5 * a_theta) 
    fig.subplots_adjust(left=-0.1, bottom=-0.05, right=1., top=1.05, 
                        wspace=-0.1, hspace=-0.1) 
    for j in range(1, 5): 
        fig.add_subplot(2, 2, j, projection='polar', 
                        axis_bgcolor=(1., 1., 1., 0.)) 
        ax = fig.gca() 
        ax.bar(a_theta, a, width=np.pi/8, color='w') 
        ax.spines['polar'].set_visible(False) 
        ax.set_xticklabels([]) 
        ax.set_yticklabels([]) 
        ax.xaxis.grid(False) 
        ax.yaxis.grid(False) 
    plt.savefig('foo2.png') 
    return fig 

请您参考如下方法:

我认为您在调整地 block 之间的重叠方面走在正确的轨道上。如果重新打开网格,您可以看到这些图已经在 schematic0 中相互碰撞并在 schematic2 中重叠。我不确定是否有比乱用 subplots_adjust 命令更好的方法来摆脱空白,例如:

fig.subplots_adjust(left=-0.3, bottom=-0.05, right=1., top=1.05, 
                    wspace=-0.45, hspace=-0.15)