Python 2.7 子批次数为奇数的matplotlib

Python 2.7 子批次数为奇数的matplotlib,python-2.7,matplotlib,Python 2.7,Matplotlib,我正在尝试创建一个plotting函数,该函数将所需绘图的数量作为输入,并使用pylab.subplot和sharex=True选项进行绘图。如果所需的绘图数量是奇数,那么我想删除最后一个面板,并强制在其正上方的面板上添加勾号标签。我找不到同时使用sharex=True选项的方法。子批次的数量可能相当大(>20) 下面是示例代码。在本例中,我想在I=3时强制选择xtick标签 import numpy as np import matplotlib.pylab as plt def main(

我正在尝试创建一个plotting函数,该函数将所需绘图的数量作为输入,并使用
pylab.subplot
sharex=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()

如果将
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()
它应该做到这一点:


简单地说,您让子地块调用偶数(在本例中为6个地块):

然后删除不需要的:

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

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

对于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]) 

我一直生成任意数量的子地块(有时数据会导致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
这将产生以下结果:

或者,切换到按列遍历顺序(
generate_sublots(…,row_-wise=False)
)将生成:


在处理大量轴对象(子地块)时,使用
delaxes
似乎效率低下。我用
add_subplot
完成了这项工作。但我不确定如何获得
子地块
提供的
sharex
sharey
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
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()