2017-09-25 5 views
0

Sevoorn/matplotlib를 사용할 때 x 축 값이 바의 레이블과 정확하게 관련이없는 것처럼 보이는 문제가 있습니다. 나는이 다음과 같은 코드를 사용하여 그래프 때matplotlib x 축의 시작점을 설정하는 방법은 무엇입니까?

hypothesis1_df: 

    revol_util deviation 
20   20 -37.978539 
21   21 -27.313996 
22   22 -23.790328 
23   23 -19.729957 
24   24 -16.115686 
..   ...  ... 
96   96 67.275585 
97   97 91.489382 
98   98 60.967792 
99   99 48.385094 
100   100 77.852812 

지금 문제가 : 참고로, 내가 좋아하는 뭔가 나를 남겨두고 pandas.DataFrame 객체를 가지고 데이터에 대한 상세한 설명을 보여 처음 20 개 행을 감소 :

Image1

참고 x 축 값을 그들이 20에서 시작하지 않는 방법은 t이다 :

import pandas as pd 
import seaborn as sns 
import matplotlib.pyplot as plt 
import matplotlib.ticker as ticker 

ax = sns.barplot(x='revol_util', y='deviation', data=hypothesis1_df) 
ax.set(xlabel="Revolving Credit Utilization (%)", 
      ylabel="Deviation from Mean (%)", 
      title="Credit Utilization and Likelihood of Late Payments\n(20 - 100%)") 
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d')) # Format axis ticks as int 
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=10)) # Set tick label frequency = base 

plt.show() 

나는이 얻을 티커를 상쇄 할 방법이 있습니까? 나는 ax.set_xlim(xmin=20, xmax=100)을 시도했으나 그래프의 아래쪽 20 개를 잘라 내고 오른쪽 20 개를 빈 공간으로 확장했습니다. 모든 축 형식을 제거하면 레이블이 올바르게 지정되지만 모든 레이블이 나열되기 때문에 너무 바쁩니다. 도와 주셔서 감사합니다.

답변

-1

시도 : ax.set_xticklabels(hypothesis1_df.index.tolist()) 수동으로 x 축 레이블을 설정하십시오.

+0

불행하게도 그것은 그대로은'MultipleLocator'와 함께 사용하면 균등 범위 21 ~ 29 확산 라벨 나에게주는 것, 그리고 내가'MultipleLocator' 라인을 제거 한 후 그것을 시도하는 경우 (읽기에는 너무 바빠서) 범위의 모든 값이 끝납니다. 'ax.set_xticklabels (np.arange (20, 100, 10)'을 사용하면 라벨이 붙지 만 처음 8자를 할당하고 나머지는 공백으로 남김 – Brendan

+0

'Ax '뒤에'MultipleLocator' 행을 호출 해 보았습니까? set_xticklabels (가설 1_df.index.tolist())'행? –

-1

문제는 seaborn 막대 그림에서 막대가 실제로 0,1,...,N-1에 위치한다는 것입니다. 해당 레이블은 해당 데이터에 해당하는 숫자에 FixedLocator으로 설정됩니다.

따라서 할 수있는 옵션 : 우리가 시본 barplot의 진드기는 항상 0에서 시작하는 것이 알고 있기 때문에 수동으로

ax.xaxis.set_major_locator(ticker.MultipleLocator(10)) 
    ax.set_xticklabels(df.index.tolist()[::10]) # take every tenth label from list 
0

, 우리는 단지의 첫 번째 값을 추가 할 수있는 여러 로케이터를 사용하고 ticklabels을 설정하여 matplotlib.ticker.FuncFormatter의 현재 틱에 대한 revol_util 값은 기존 MultipleLocator과 함께 표시됩니다.

import numpy as np 
import pandas as pd 
import seaborn as sns 
import matplotlib.pyplot as plt 
import matplotlib.ticker as ticker 

# A fake dataframe 
hypothesis1_df = pd.DataFrame({ 
    'revol_util':np.arange(20, 101, 1), 
    'deviation':np.arange(-40, 81, 1.5) + np.random.rand(81)*10.}) 
hypothesis1_df = hypothesis1_df.set_index('revol_util', drop=False) 

ax = sns.barplot(x='revol_util', y='deviation', data=hypothesis1_df) 
ax.set(xlabel="Revolving Credit Utilization (%)", 
      ylabel="Deviation from Mean (%)", 
      title="Credit Utilization and Likelihood of Late Payments\n(20 - 100%)") 

ax.xaxis.set_major_locator(ticker.MultipleLocator(10)) 
ax.xaxis.set_major_formatter(ticker.FuncFormatter(
    lambda x, pos: '{:g}'.format(x + hypothesis1_df['revol_util'].iloc[0]))) 

plt.show() 

enter image description here

관련 문제