2

I am trying to add a small line outside of my axis range which I want to use as a highly customized legend at a later stage. However, using axes.hlines changes the xlim of my axis, even though I specify transform = axes.transAxes. The xlim appears to be set such that the coordinates of the hlines are included in the datacoordinate range. Only, that these coordinates are meant to be axes coordinates, not data coordinates.

Here comes a minimal working example:

import numpy as np
import matplotlib.pyplot as plt

x_data = np.random.rand(10)+10
y_data = np.random.rand(10)

fig, ax = plt.subplots()

ax.scatter(x_data,y_data)
ax.hlines(0.5,1.1,1.2, transform = ax.transAxes, clip_on = False)

results in xlims being changed by the ax.hlines command:

enter image description here

while with ax.hlines being commented out one gets:

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82
Olmo
  • 325
  • 4
  • 13
  • Using `ax.hlines` calls `autoscale_view` under the hood, which is the line which is altering your x limit. I don't know if this is a bug or it is intended though. You can stop this happening by setting the x limits yourself using `ax.set_xlim(10, 11)`. However, I don't know if this is applicable in your actual code – DavidG Apr 20 '20 at 09:29
  • Thanks DavidG, to me this seems to be a highly dysfunctional behavior, since whenever you add something to your plot using axis coordinates, you obviously do not want your data coordinate range to change! your workaround of course fixes this. I do create several plots in loop and therefore I am using temp = axes.get_xlim(), ax.hlines, axes.set_xlim(temp) in combination, which is okay, but not great. – Olmo Apr 20 '20 at 12:04
  • 1
    One workaround is `xlims = ax.get_xlim()`, then `ax.hlines(...)` and finally `ax.set_xlim(xlims)` – JohanC Apr 20 '20 at 15:19

0 Answers0