具有奇数个子图的matplotlib

ocebsuys  于 2023-03-13  发布在  其他
关注(0)|答案(5)|浏览(143)

我尝试创建一个绘图函数,它将所需的绘图数量作为输入,并使用pylab.subplotssharex=True选项进行绘图。然后我想删除最后一个面板,并将刻度标签强制放在面板的正上方。我找不到一种方法来同时使用sharex=True选项。子区的数量可以相当大(〉20)。
下面是示例代码。在这个示例中,我希望在i=3时强制使用xtick标签。

import numpy as np
import matplotlib.pylab as plt

def main():
    n = 5
    nx = 100
    x = np.arange(nx)
    if n % 2 == 0:
        f, axs = plt.subplots(n/2, 2, sharex=True)
    else:
        f, axs = plt.subplots(n/2+1, 2, sharex=True)
    for i in range(n):
        y = np.random.rand(nx)
        if i % 2 == 0:
            axs[i/2, 0].plot(x, y, '-', label='plot '+str(i+1))
            axs[i/2, 0].legend()
        else:
            axs[i/2, 1].plot(x, y, '-', label='plot '+str(i+1))
            axs[i/2, 1].legend()
    if n % 2 != 0:
        f.delaxes(axs[i/2, 1])
    f.show()

if __name__ == "__main__":
     main()
eqqqjvef

eqqqjvef1#

简单地说,你让你的子图调用一个偶数(在本例中为6个图):

f, ax = plt.subplots(3, 2, figsize=(12, 15))

然后删除不需要的内容:

f.delaxes(ax[2,1]) # The indexing is zero-based here

这个问题和回答是以一种自动化的方式来看待这个问题的,但是我认为在这里发布基本的用例是值得的。

ckx4rj1h

ckx4rj1h2#

如果将main函数中的最后一个if替换为:

if n % 2 != 0:
    for l in axs[i/2-1,1].get_xaxis().get_majorticklabels():
        l.set_visible(True)
    f.delaxes(axs[i/2, 1])

f.show()

它应该可以做到:

z8dt9xmd

z8dt9xmd3#

我总是生成任意数量的子图(有时数据会导致3个子图,有时13个子图,等等),我写了一个小效用函数来避免思考它。
我定义的两个函数如下所示。您可以更改样式选择以匹配您的偏好。

import math
import numpy as np
from matplotlib import pyplot as plt

def choose_subplot_dimensions(k):
    if k < 4:
        return k, 1
    elif k < 11:
        return math.ceil(k/2), 2
    else:
        # I've chosen to have a maximum of 3 columns
        return math.ceil(k/3), 3

def generate_subplots(k, row_wise=False):
    nrow, ncol = choose_subplot_dimensions(k)
    # Choose your share X and share Y parameters as you wish:
    figure, axes = plt.subplots(nrow, ncol,
                                sharex=True,
                                sharey=False)

    # Check if it's an array. If there's only one plot, it's just an Axes obj
    if not isinstance(axes, np.ndarray):
        return figure, [axes]
    else:
        # Choose the traversal you'd like: 'F' is col-wise, 'C' is row-wise
        axes = axes.flatten(order=('C' if row_wise else 'F'))

        # Delete any unused axes from the figure, so that they don't show
        # blank x- and y-axis lines
        for idx, ax in enumerate(axes[k:]):
            figure.delaxes(ax)

            # Turn ticks on for the last ax in each column, wherever it lands
            idx_to_turn_on_ticks = idx + k - ncol if row_wise else idx + k - 1
            for tk in axes[idx_to_turn_on_ticks].get_xticklabels():
                tk.set_visible(True)

        axes = axes[:k]
        return figure, axes

以下是13个子图的使用示例:

x_variable = list(range(-5, 6))
parameters = list(range(0, 13))

figure, axes = generate_subplots(len(parameters), row_wise=True)
for parameter, ax in zip(parameters, axes):
    ax.plot(x_variable, [x**parameter for x in x_variable])
    ax.set_title(label="y=x^{}".format(parameter))

plt.tight_layout()
plt.show()

它产生以下结果:

或者,切换到列遍历顺序(generate_subplots(..., row_wise=False))将生成:

a2mppw5e

a2mppw5e4#

您可以检查没有打印的子图,而不是通过计算来检测需要删除的子图。您可以查看this answer中的各种方法,以检查是否在轴上绘制了某些内容。使用函数ax.has_Data(),您可以将函数简化为:

def main():
    n = 5
    max_width = 2 ##images per row
    height, width = n//max_width +1, max_width
    fig, axs = plt.subplots(height, width, sharex=True)

    for i in range(n):
        nx = 100
        x = np.arange(nx)
        y = np.random.rand(nx)
        ax = axs.flat[i]
        ax.plot(x, y, '-', label='plot '+str(i+1))
        ax.legend(loc="upper right")

    ## access each axes object via axs.flat
    for ax in axs.flat:
        ## check if something was plotted 
        if not bool(ax.has_data()):
            fig.delaxes(ax) ## delete if nothing is plotted in the axes obj

    fig.show()

您还可以使用n参数指定所需的图像数,使用max_width参数指定每行所需的图像数。

ygya80vv

ygya80vv5#

对于Python 3,可以按如下方式删除:

# I have 5 plots that i want to show in 2 rows. So I do 3 columns. That way i have 6 plots.
f, axes = plt.subplots(2, 3, figsize=(20, 10))

sns.countplot(sales_data['Gender'], order = sales_data['Gender'].value_counts().index, palette = "Set1", ax = axes[0,0])
sns.countplot(sales_data['Age'], order = sales_data['Age'].value_counts().index, palette = "Set1", ax = axes[0,1])
sns.countplot(sales_data['Occupation'], order = sales_data['Occupation'].value_counts().index, palette = "Set1", ax = axes[0,2])
sns.countplot(sales_data['City_Category'], order = sales_data['City_Category'].value_counts().index, palette = "Set1", ax = axes[1,0])
sns.countplot(sales_data['Marital_Status'], order = sales_data['Marital_Status'].value_counts().index, palette = "Set1", ax = axes[1, 1])

# This line will delete the last empty plot
f.delaxes(ax= axes[1,2])

相关问题