2014-12-16 21 views
5

I dati che sto visualizzando ha senso solo se si tratta di numeri interi.come forzare matplotlib per visualizzare solo numeri interi sull'asse Y

I.e. 0,2 di un record non ha senso in termini del contesto delle informazioni che sto analizzando.

Come si impone a Matplotlib di utilizzare solo numeri interi sull'asse Y. Cioè 1, 100, 5 ecc.? non 0,1, 0,2 ecc.

for a in account_list: 
    f = plt.figure() 
    f.set_figheight(20) 
    f.set_figwidth(20) 
    f.sharex = True 
    f.sharey=True 

    left = 0.125 # the left side of the subplots of the figure 
    right = 0.9 # the right side of the subplots of the figure 
    bottom = 0.1 # the bottom of the subplots of the figure 
    top = 0.9  # the top of the subplots of the figure 
    wspace = 0.2 # the amount of width reserved for blank space between subplots 
    hspace = .8 # the amount of height reserved for white space between subplots 
    subplots_adjust(left=left, right=right, bottom=bottom, top=top, wspace=wspace, hspace=hspace) 

    count = 1 
    for h in headings: 
     sorted_data[sorted_data.account == a].ix[0:,['month_date',h]].plot(ax=f.add_subplot(7,3,count),legend=True,subplots=True,x='month_date',y=h) 

     #set bottom Y axis limit to 0 and change number format to 1 dec place. 
     axis_data = f.gca() 
     axis_data.set_ylim(bottom=0.) 
     from matplotlib.ticker import FormatStrFormatter 
     axis_data.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) 

     #This was meant to set Y axis to integer??? 
     y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) 
     axis_data.yaxis.set_major_formatter(y_formatter) 

     import matplotlib.patches as mpatches 

     legend_name = mpatches.Patch(color='none', label=h) 
     plt.xlabel("") 
     ppl.legend(handles=[legend_name],bbox_to_anchor=(0.,1.2,1.0,.10), loc="center",ncol=2, mode="expand", borderaxespad=0.) 
     count = count + 1 
     savefig(a + '.png', bbox_inches='tight') 
+0

Non sono sicuro del motivo per cui si sta svendendo. È una domanda buona e chiara con una risposta non molto ovvia (oltre l'impostazione manuale dei ticks, che è inflessibile). –

risposta

1

È possibile modificare le etichette/numeri di graduazione come segue. Questo è solo un esempio, in quanto non hai fornito alcun codice che hai, quindi non sei sicuro che si applichi o meno a te.

import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 

fig.canvas.draw() 

# just the original labels/numbers and modify them, e.g. multiply by 100 
# and define new format for them. 
labels = ["{:0.0f}".format(float(item.get_text())*100) 
       for item in ax.get_xticklabels()] 


ax.set_xticklabels(labels) 

plt.show() 

senza modifiche asse x:

enter image description here

con la modifica:

enter image description here

10

Il modo più flessibile è specificare integer=True al localizzatore predefinito zecca (MaxNLocator) fare qualcosa di simile a questo:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.ticker as ticker 

fig, ax = plt.subplots() 

# Be sure to only pick integer tick locations. 
for axis in [ax.xaxis, ax.yaxis]: 
    axis.set_major_locator(ticker.MaxNLocator(integer=True)) 

# Plot anything (note the non-integer min-max values)... 
x = np.linspace(-0.1, np.pi, 100) 
ax.plot(0.5 * x, 22.8 * np.cos(3 * x), color='black') 

# Just for appearance's sake 
ax.margins(0.05) 
ax.axis('tight') 
fig.tight_layout() 

plt.show() 

enter image description here

In alternativa, è possibile impostare manualmente le posizioni di graduazione/etichette come Marcin e Joel suggeriscono (o utilizzare un MultipleLocator). Il lato negativo di questo è che è necessario capire quali posizioni di tick hanno senso, piuttosto che avere matplotlib selezionare un intervallo di tick intero ragionevole basato sui limiti dell'asse.

+0

Grazie @Joe Kington - Puoi aiutarmi? Sento che sto usando male: ottengo l'errore: axis_data.set_major_locator (ticker.MaxNLocator (integer = True)) L'oggetto 'AxesSubplot' non ha attributo 'set_major_locator'. È perché sto provando a impostare l'asse Y in numeri interi per SUBPLOTS? – yoshiserry

+0

@yoshiserry - Suppongo che tu stia cercando di chiamare "ax.set_major_locator' invece di" ax.yaxis.set_major_locator'. Il tick locator è un attributo dell '"Asse" (cioè asse x/y), non degli "Asce" (cioè la trama). Prova 'axis_data.yaxis.set_major_locator' (o' xaxis', a seconda). –

1

Se è solo l'asseY che si desidera modificare, un modo semplice è quello di determinare quali zecche si desidera:

tickpos = [0,1,4,6] 

py.yticks(tickpos,tickpos) 

metterà zecche a 0, 1, 4 e 6. Più in generale

py.yticks([0,1,2,3], ['zero', 1, 'two', 3.0]) 

inserirà l'etichetta del secondo elenco nella posizione del primo elenco. Se l'etichetta sarà lo yvalue, è una buona idea usare la versione py.yticks(tickpos,tickpos) solo per assicurarsi che ogni volta che si cambiano le posizioni dei tick, le etichette ottengano la stessa modifica.

Più in generale, tuttavia, la risposta di Kington consente di dire a pylab solo numeri interi per l'asse y, ma lascia che scelga dove vanno i segni di graduazione.

Problemi correlati