2013-10-09 30 views
12

我試圖繪製散佈矩陣。我正在建立在此線程Is there a function to make scatterplot matrices in 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)技巧。但是這似乎只爲最後一個小區進行旋轉。

回答

20

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) 
+8

+1在附註中,只是迭代'axes.flat'而不是遍​​歷所有i,j對就會更容易。此外,您可以使用'plt.setp(ax.get_xticklabels(),rotation = 45)'而不是遍​​歷每個刻度標籤。不過,這只是一個風格問題。 –

+0

同意,但是i,j迭代已經存在,並且僅使用所有軸的子集,因此不需要旋轉隱藏的標籤。 'setp'確實是一個很好的補充,我想不出一個'斧頭'的做法,這是一個竅門! –

13

只是遍歷綁在圖中的座標軸,設置爲重複對象的活動軸,並修改:

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