pythonmatplotlibxticksyticks

Tick labels position


I want to plot a roc curve, but the tick label 0.0 appears at both axes, I removed one tick label by directly setting the labels:

pl.gca().set_yticks([0.2, 0.4, 0.6, 0.8, 1.0])
pl.gca().set_xticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0])

enter image description here

How can the tick label "0.0" of the x-axis aligned with the y-axis? The label should be moved to the left border of the y-axis, that it begins at the same vertical position as the other tick labels in the y-axis.


Solution

  • I think you want to prune x-axis:

    #!/usr/bin/env python3
    
    import matplotlib
    from matplotlib import pyplot as plt
    from matplotlib.ticker import MaxNLocator
    
    data = range(5)
    
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    ax.plot(data,data)
    
    ax.xaxis.set_major_locator(MaxNLocator(5, prune='lower'))
    ax.yaxis.set_major_locator(MaxNLocator(4))
    
    fig.savefig("1.png")
    

    enter image description here

    Edit:

    Sad but true: matplotlib was not meant for a crossed axes 2D plots. If You sure the zero for both axis is at the lower left box corner than I suggest to put it there manually:

    #!/usr/bin/env python3
    
    import matplotlib
    from matplotlib import pyplot as plt
    from matplotlib.ticker import MaxNLocator
    
    data = range(5)
    
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    ax.plot(data,data)
    
    ax.xaxis.set_major_locator(MaxNLocator(5, prune='lower'))
    ax.yaxis.set_major_locator(MaxNLocator(4, prune='lower'))
    
    fig.tight_layout()
    
    ax.text(-0.01, -0.02,
            "0",
            horizontalalignment = 'center',
            verticalalignment = 'center',
            transform = ax.transAxes)
    
    fig.savefig("1.png")
    

    enter image description here

    Here one can adjust the zero position manually.

    Personally I prune x or y axis depending on situation, and happy with that.