2015-02-02 2 views
3

텍스트 레이블을 그래프의 x 티커와 어떻게 정렬해야합니까? 나는 host.set_xticklabels (라벨, 회전 = '수직')을 사용하고 있지만, 그것이 작동하지 않는 것 같습니다. 내 레이블은 문장이고 일부는 "미이라 파트 2"와 같이 다른 레이블보다 크기가 작거나 클 수 있습니다.이를 수용하기 위해 x 축 아래 공간을 어떻게 채 웁니까? matplotlib의 x 축에 텍스트 레이블을 3 개의 플롯으로 정렬/회전

from mpl_toolkits.axes_grid1 import host_subplot 
import mpl_toolkits.axisartist as AA 
import matplotlib.pyplot as plt 
import pandas as pd 
import numpy as np 

path='/home/project/df.csv' 
df=pd.read_csv(path,sep=',',header='infer') 
xs =range(0,101) 
ys =list(df['B'].ix[0:100]) 
zs=list(df['C'].ix[0:100]) 
ws=list(df['D'].ix[0:100]) 

if 1: 
    host = host_subplot(111, axes_class=AA.Axes) 
    p1, = host.plot(xs, ys, label='B') 
    plt.subplots_adjust(right=0.75) 

    par1 = host.twinx() 
    par2 = host.twinx() 

    offset = 60 
    new_fixed_axis = par2.get_grid_helper().new_fixed_axis 
    par2.axis["right"] = new_fixed_axis(loc="right", 
             axes=par2, 
             offset=(offset, 0)) 

    par2.axis["right"].toggle(all=True) 
    host.set_xlim(min(xs), max(xs)) 
    host.set_ylim(100, max(ys)) 

    host.set_xlabel("A") 
    host.set_ylabel("B") 
    par1.set_ylabel("C") 
    par2.set_ylabel("D") 

    p2, = par1.plot(xs, ws, label='C',color='red') 
    p3, = par2.plot(xs, zs, label='D',color='green') 
    for tl in par1.get_yticklabels(): 
     tl.set_color('red') 
    for tl in par2.get_yticklabels(): 
     tl.set_color('green') 



    for tl in par1.get_yticklabels(): 
     tl.set_color('r') 
    for tl in par2.get_yticklabels(): 
     tl.set_color('g') 
    host.legend() 

    host.axis["left"].label.set_color(p1.get_color()) 
    par1.axis["right"].label.set_color(p2.get_color()) 
    par2.axis["right"].label.set_color(p3.get_color()) 
    start, end, stepsize=0,len(df)-1,3 
    host.xaxis.set_ticks(np.arange(start, end, stepsize)) 
    labels=list(df['A'])[0::stepsize] 
    host.set_xticklabels(labels,rotation='vertical') 
    plt.tight_layout() 
    plt.draw() 
    plt.show() 

enter image description here

나는 그림에서와 같이 "블랙"질량을 정렬 할 필요가있다.

여기 예제 python rotate values on xaxis to not overlap - plt.xticks (x, labels, rotation = 'vertical') 등의 제안을 시도했지만 작동하지 않았습니다.

편집 - 아래 Kazemakaze의 피드백에서 , 여기에 내가 뭘하려입니다 - : F, 호스트 = plt.subplots는() #host = host_subplot (111, axes_class = AA.Axes) 하지만 적응해야 나머지 코드도 마찬가지입니다. 이것이 작동하는 twinx 축이있는 예제를 제공 할 수 있습니까?

내 코드를 Secondary axis with twinx(): how to add to legend?에 적용하고 회전이 작동하며, 보조 축의 포인터가 필요합니다 ().

+0

사진에서보기가 어렵습니다. 라벨이 제대로 회전하지 않습니까? – kazemakase

+0

글자를 그릴 때 [0:10] - 회전이 무엇이든 상관없이 모든 것을 직선으로 볼 수 있습니다. 무작위로 샘플 데이터를 사용해보십시오. 편집 할 때 레이블 텍스트를 게시 할 수 있습니다. – ekta

+0

샘플 라벨을 사용해보십시오 - [ "mummy returns", "lila", "ringa ringa roses", "아름다운 하루"] * 10 [무작위 데이터의 레코드 수는 무엇이든간에] – ekta

답변

3

가 여기에 내가 host_subplot와 참이었다 - 그것을에게 회전하지 않는 문제를 해결하고

enter image description here

import matplotlib.pyplot as plt 
import pandas as pd 
import numpy as np 

path='/home/project/df.csv' 
df=pd.read_csv(path,sep=',',header='infer') 
xs =range(0,101) 
ys =list(df['B'].ix[0:100]) 
zs=list(df['C'].ix[0:100]) 
ws=list(df['D'].ix[0:100]) 


def make_patch_spines_invisible(ax): 
    ax.set_frame_on(True) 
    ax.patch.set_visible(False) 
    for sp in ax.spines.itervalues(): 
     sp.set_visible(False) 


def three_way_plot(xs,ys,ws,zs,category): 
    fig, host = plt.subplots() 
    fig.subplots_adjust(right=0.6) 
    par1 = host.twinx() 
    par2 = host.twinx() 
    par2.spines["right"].set_position(("axes", 1.1)) 
    p1, = host.plot(xs, ys, "blue", linewidth=2.0, label="B") 
    p2, = par1.plot(xs, ws, "r-", label="C") 
    p3, = par2.plot(xs, zs, "g-", label="D") 
    host.set_xlim(min(xs), max(xs)) 
    host.set_ylim(min(ys), max(ys) + 200) 
    par1.set_ylim(min(ws), max(ws) + 200) 
    par2.set_ylim(min(zs), max(zs)) 
    host.set_xlabel("A", fontsize=14) 
    host.set_ylabel("B", fontsize=14) 
    par1.set_ylabel("C", fontsize=14) 
    par2.set_ylabel("D", fontsize=14) 
    host.yaxis.label.set_color(p1.get_color()) 
    par1.yaxis.label.set_color(p2.get_color()) 
    par2.yaxis.label.set_color(p3.get_color()) 
    lines = [p1, p2, p3] 
    labels = ["mary had a little lamb","The mummy returns","Die another day","Welcome back"]*25 
    start, end, step_size = 0, len(df) - 1, 4 
    host.set_xticks(np.arange(start, end, step_size)) 
    host.set_xticklabels(labels, rotation='vertical', fontsize=10) 
    host.legend(lines, [l.get_label() for l in lines]) 
    plt.tight_layout() 
    plt.show() 


three_way_plot(xs,ys,ws,zs,"category") 

당연히 plt.subplot

를 사용하는 경우 제대로 작동 방법, 나는 데이터의 진정한 레이블을 마스크.

관련 문제