2016-12-03 2 views
1

Как избавиться от двух нулей на пересечении осей (происхождение)? Есть ли какой-либо общий способ (не жестко закодированный: , чтобы удалить этот ярлык метки) в matplotlib? Также неплохо разместить нуль около ось (независимо от того, x или y).Один нуль в начале координат

x = np.linspace(-np.pi, np.pi, 256, endpoint=True) 
C, S = np.cos(x), np.sin(x) 

plt.plot(x, C, label='cosine') 
plt.plot(x, S, label='sine') 

ax = plt.gca() 

ax.spines['right'].set_color('none') 
ax.spines['top'].set_color('none') 
ax.xaxis.set_ticks_position('bottom') 
ax.spines['bottom'].set_position(('data',0)) 
ax.yaxis.set_ticks_position('left') 
ax.spines['left'].set_position(('data',0)) 

plt.show() 

enter image description here

ответ

2

Я предполагаю, что у вас есть одна альтернатива для создания пользовательских formatter для обозначения пересечения оси.

import matplotlib.pylab as plt 
import numpy as np 
import matplotlib as mpl 

def center_spines(ax, centerx=0, centery=0): 
    """Centers the axis spines at <centerx, centery> on the axis 'ax' """ 

    # Set the axis's spines to be centered at the given point 
    # (Setting all 4 spines so that the tick marks go in both directions) 
    ax.spines['left'].set_position(('data', centerx)) 
    ax.spines['bottom'].set_position(('data', centery)) 
    ax.spines['right'].set_position(('data', centerx - 1)) 
    ax.spines['top'].set_position(('data', centery - 1)) 

    # Hide the line (but not ticks) for "extra" spines 
    for side in ['right', 'top']: 
     ax.spines[side].set_color('none') 

    # On both the x and y axes 
    for axis, center in zip([ax.xaxis, ax.yaxis], [centerx, centery]): 
     # Hide the ticklabels at <centerx, centery> 
     formatter = CenteredFormatter() 
     formatter.center = center 
     axis.set_major_formatter(formatter) 

    # Add offset ticklabels at <centerx, centery> using annotation 
    # (Should probably make these update when the plot is redrawn...) 
    xlabel, ylabel = map(formatter.format_data, [centerx, centery]) 
    ax.annotate('%s' % xlabel, (centerx, centery), 
      xytext=(2.5, 4), textcoords='offset points', 
      ha='right', va='top') 

    ax.xaxis.set_ticks_position('bottom') 
    ax.yaxis.set_ticks_position('left') 

# Custom formatter 
class CenteredFormatter(mpl.ticker.ScalarFormatter): 
    """Acts exactly like the default Scalar Formatter, but yields an empty 
    label for ticks at "center".""" 
    center = 0 
    def __call__(self, value, pos=None): 
     if value == self.center: 
      return '' 
     else: 
      return mpl.ticker.ScalarFormatter.__call__(self, value, pos) 

# Main 
x = np.linspace(-np.pi, np.pi, 256, endpoint=True) 
C, S = np.cos(x), np.sin(x) 

plt.plot(x, C, label='cosine') 
plt.plot(x, S, label='sine') 

ax = plt.gca() 
center_spines(ax) 
plt.show() 

enter image description here Кодекс основан на этом примере: Center origin in matplotlib

+0

Это (много) лучше, чем по умолчанию, но если бы хорошо, если происхождение было то же самое вертикальное смещение как рентгеновскими этикетки и горизонтальная смещение y-меток. – KeithWM

Смежные вопросы