xlim is not auto scaled when using twinx · Issue #16723 · matplotlib/matplotlib · GitHub
Skip to content

xlim is not auto scaled when using twinx #16723

Description

@01baftb

I am reporting as possible bug.

When plotting a secondary y axis on the right, the xlim is not being properly auto scaled. As possible work around was proposed here, https://stackoverflow.com/a/27344398/4988010, however, it seems this was fixed here, 26ed35b. However, I am not seeing the issue being resolved on matplotlib v3.2.0.

%matplotlib widget
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
decay = lambda C, K, x: C *(1-np.exp(-1*K*x))
x = np.linspace(0,10,10)

# Create a secondary y axis on the right
twin_ax = ax.twinx()

for n in range(5):
    C = n**2 + 5
    K = 0.75
    # Plot the exponential decay on left y axis 
    ax.plot(x,decay(C,K,x), marker='o', linestyle='--', label=C)
    # Plot the limit of decay on right y axis 
    twin_ax.axhline(y=C, color='gray') 
    
ax.legend()
ax.set_xlabel('X')
ax.set_ylabel('Measured values')
twin_ax.set_ylabel('Theoritical limit')

# Align the both left and right y axis 
twin_ax.set_ylim(ax.get_ylim())

##################
# Issues or bugs
# Need to fix the X limits or else 
# the graph doens't display properly
##################

print('xlim before fix: {}'.format(ax.get_xlim()))
ax.relim()
print('xlim after relim(): {}'.format(ax.get_xlim()))
# A hack to fix the issue # https://stackoverflow.com/a/27344398/4988010
twin_ax.plot(0, 0, visible=False)
print('xlim after fixing: {}'.format(ax.get_xlim()))

plt.show()

plot with issue
plot with working hack

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: closed as inactiveIssues closed by the "Stale" Github Action. Please comment on any you think should still be open.status: inactiveMarked by the “Stale” Github Action

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions