图的原点为零

时间:2016-12-03 23:34:59

标签: python matplotlib

如何摆脱轴交叉点(原点)的两个零点?在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

1 个答案:

答案 0 :(得分: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