pythonnumpymatplotlibxticks

Move x-axis to data=0 but keep tick labels at the bottom


I would like to move the line of the x-axis (with all the corresponding ticks) x=0. But the tick-labels should be positioned at the bottom of the figure, to prevent clutter in the graph.

Show axis at center, but keep labels on the left

from matplotlib import pyplot as plt
import matplotlib.transforms as transforms
import numpy as np

# Generate some sample data
x = np.linspace(-10, 10, 100)
y = np.sin(x)

# Create the plot
fig, ax = plt.subplots()
# Plot the data
ax.plot(x, y)
# Move the x-axis to the bottom
ax.spines['bottom'].set_position(('data', 0))
trans = transforms.blended_transform_factory(ax.transAxes,ax.transData)
# plt.setp(ax.get_xticklabels(), 'transform', trans)  # this returns a plot with zero height
plt.show()

I would like to move the axis itself including the ticks. This makes working with a grid and logarithmic scale for the ticks easier. Therefore a solution with a horizontal line lke ax.axhline(y=0) is not a good solution and is not what I am looking for.


Solution

  • IIUC you're looking to apply the transformer on the xaxis, like this:

    trans = transforms.blended_transform_factory(ax.transData,ax.transAxes)
    plt.setp(ax.get_xticklabels(), 'transform', trans)
    plt.show()
    

    Output:

    enter image description here