每个子图旋转轴标签文本

31

我正在尝试绘制散点矩阵。我正在基于这个主题中给出的示例构建 在matplotlib中是否有一个制作散点图矩阵的函数?。在这里,我仅稍微修改了代码,使所有子图的坐标轴可见。修改后的代码如下:

import itertools
import numpy as np
import matplotlib.pyplot as plt

def main():
    np.random.seed(1977)
    numvars, numdata = 4, 10
    data = 10 * np.random.random((numvars, numdata))
    fig = scatterplot_matrix(data, ['mpg', 'disp', 'drat', 'wt'],
            linestyle='none', marker='o', color='black', mfc='none')
    fig.suptitle('Simple Scatterplot Matrix')
    plt.show()

def scatterplot_matrix(data, names, **kwargs):
    """Plots a scatterplot matrix of subplots.  Each row of "data" is plotted
    against other rows, resulting in a nrows by nrows grid of subplots with the
    diagonal subplots labeled with "names".  Additional keyword arguments are
    passed on to matplotlib's "plot" command. Returns the matplotlib figure
    object containg the subplot grid."""
    numvars, numdata = data.shape
    fig, axes = plt.subplots(nrows=numvars, ncols=numvars, figsize=(8,8))
    fig.subplots_adjust(hspace=0.05, wspace=0.05)

    for ax in axes.flat:
        # Hide all ticks and labels
        ax.xaxis.set_visible(True)
        ax.yaxis.set_visible(True)

#        # Set up ticks only on one side for the "edge" subplots...
#        if ax.is_first_col():
#            ax.yaxis.set_ticks_position('left')
#        if ax.is_last_col():
#            ax.yaxis.set_ticks_position('right')
#        if ax.is_first_row():
#            ax.xaxis.set_ticks_position('top')
#        if ax.is_last_row():
#            ax.xaxis.set_ticks_position('bottom')

    # Plot the data.
    for i, j in zip(*np.triu_indices_from(axes, k=1)):
        for x, y in [(i,j), (j,i)]:
            axes[x,y].plot(data[x], data[y], **kwargs)

    # Label the diagonal subplots...
    for i, label in enumerate(names):
        axes[i,i].annotate(label, (0.5, 0.5), xycoords='axes fraction',
                ha='center', va='center')

    # Turn on the proper x or y axes ticks.
    for i, j in zip(range(numvars), itertools.cycle((-1, 0))):
        axes[j,i].xaxis.set_visible(True)
        axes[i,j].yaxis.set_visible(True)
    fig.tight_layout()
    plt.xticks(rotation=45)
    fig.show()
    return fig

main()

我似乎无法旋转所有子图的x轴文本。如图所示,我尝试了plt.xticks(旋转45度)的技巧。但是这似乎仅对最后一个子图执行旋转。

3个回答

55

只需遍历与图形相关联的轴,将活动轴设置为迭代对象,并进行修改:

for ax in fig.axes:
    matplotlib.pyplot.sca(ax)
    plt.xticks(rotation=90)

1
解决了我的问题! - MarkS

34

plt 只作用于当前活动的坐标轴。你应该将它放在最后一个循环内,其中你设置了一些标签的可见性为 True:

plt 只对当前处于激活状态的坐标轴起作用。您应该将其放置在您最后一个循环中,在那里您将某些标签的可见性设置为 True:

# Turn on the proper x or y axes ticks.
for i, j in zip(range(numvars), itertools.cycle((-1, 0))):
    axes[j,i].xaxis.set_visible(True)
    axes[i,j].yaxis.set_visible(True)

    for tick in axes[i,j].get_xticklabels():
        tick.set_rotation(45)
    for tick in axes[j,i].get_xticklabels():
        tick.set_rotation(45)

14
另外提一句,与其逐个遍历所有i、j对,通过在axes.flat上迭代会更容易些。此外,你可以使用plt.setp(ax.get_xticklabels(), rotation=45)来代替逐个遍历每个刻度标签。不过这只是风格问题。 - Joe Kington
同意,但是i,j迭代已经存在,并且仅使用所有轴的子集,没有必要旋转隐藏标签。setp确实是一个很好的补充,我无法想到一种一次性完成的ax.方法,这样做就可以了! - Rutger Kassies

21
for ax in fig.axes:
    ax.tick_params(labelrotation=90)


3
仅包含代码的答案通常可以通过添加一些解释来改善。如果没有一些解释,答案最终将进入审核队列。 - Jason Aller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接