2013-10-09 2 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 (rotation = 45) 트릭을 시도했습니다. 그러나 이것은 마지막 서브 플롯만을위한 회전을 수행하는 것 같습니다.

답변

20

plt은 현재 활성 축에서만 작동합니다.

# 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 모든 i, j 쌍을 순환하지 않고'axes.flat'를 반복하는 것이 훨씬 쉽습니다. 또한 각 눈금 라벨을 반복하는 대신'plt.setp (ax.get_xticklabels(), rotation = 45)'를 사용할 수 있습니다. 그것은 스타일의 문제 일뿐입니다. –

+0

동의하지만, i, j 반복이 이미 있으며 모든 축의 하위 집합 만 사용하므로 숨겨진 레이블을 회전 할 필요가 없습니다. 'setp'는 참으로 좋은 추가입니다, 나는 그것을 한 번에하는 '도끼'방법을 생각할 수 없습니다. 이것은 속임수입니다! –

13

그냥 그림에 연결된 축을 통해 반복되는 객체에 대한 활성 축을 설정 반복, 수정 : True로 레이블 가시성의 일부를 설정 어디 당신은 당신의 마지막 루프 내부에 그것을 가지고해야

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