2017-07-31 187 views
0

我有一個熊貓數據框,並且我試圖繪製兩列彼此。但問題是,我的xtick標籤正在全面精確顯示。如何縮寫(我的Xaxis值是元組)?ax.xaxis.set_major_formatter不會更改Xtick標籤顯示數字的數量

fig = plt.figure(figsize=(13,160)) 
plt.style.use('ggplot') 
sns.set_style('ticks') 
plt.rcParams['font.size'] = 12 
n = 0 

for name, group in a.groupby(['Config','prot_state','repeat','leg']): 
    ax = fig.add_subplot(20,2,n+1) 
    group = group.sort_values(by='Lambda') 

    title = name[0]+'-'+name[1]+'-'+name[2]+'('+name[3]+')' 
    ax = group.plot(y='A', x='Lambda', ax=ax, marker='o', lw=3, label='Chain_A', title=title) 
    ax = group.plot(y='B', x='Lambda', ax=ax, marker='o', lw=3, label='Chain_B', title=title) 
    ax.set_xlabel('$\lambda_{Coul}$, $\lambda_{Vdw}$') 
    ax.set_ylabel('$\Delta G$ (KJ/mol)') 
    ax.get_xaxis().get_major_formatter() 
    sns.despine(offset=10, ax=ax) 
    labels = ax.get_xticklabels() 
    plt.setp(labels, rotation=90, fontsize=10) 
    ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) 
    plt.xticks(range(len(group['Lambda'])), group['Lambda']) 

    n = n+1 

fig = ax.get_figure() 
plt.tight_layout() 
fig.savefig('{}.pdf'.format('dg-dlambda')) 

有誰知道我該如何縮寫爲兩位數?

labels = ax.get_xticklabels() 
new_labels = [] 
n_digits = 2 + 1 # you will use this for slicing the string, so the +1 is there so that your last digit doesn't get excluded. The first number (2) is arbitrary, depending how many you want. 
for i in labels: 
    new_i = str(i)[:n_digits] 
    new_labels.append(new_i) 

plt.xticks(labels, new_labels) 

但是,這會:

+2

顯示的所有'''都是''',這很難重現你的代碼,記得總是建議提供一個[Minimal,Complete,and Verifiable example](https://stackoverflow.com/help/mcve) )的問題,並編輯你的問題 關於這個問題本身,只是調用'ax.xaxis.set_major_formatter(FormatStrFormatter('%2f'))'應該做的伎倆 –

+1

可能重複的[Matplotlib:指定格式的浮點數標記](https://stackoverflow.com/questions/29188757/matplotlib-specify-format-of-floats-for-tick-lables) –

+0

我添加了ax.xaxis.set_major_formatter(FormatStrFormatter('%。1f '))到我的代碼(見上面),但它實際上沒有做任何事情 – mahzadkh

回答

1

如果您ax.xaxis.set_major_formatter(FormatStrFormatter(‘%.1f’))不起作用,你可以首先將它們轉換成字符串(只要它們的數量都以相同的順序),然​​後切片他們騙它只有在小數點前具有相同的數字位數時纔有效。

+0

謝謝,這實際上解決了問題! – mahzadkh