0

I want to shade half of the background of a scatter plot to distinguish two different regimes.

I have tried to use axvspan to do so. However, I have the problem that whenever I apply the axvspan, matplotlib adds a margin to the latter resulting in an ugly gap between the shading and the axis bounding box. How can I avoid this?

Here's what I have tried so far:

import matplotlib.pyplot as plt
import numpy as np

nsamp = 50
x = np.random.rand(nsamp)
y = np.random.rand(nsamp)

fig, ax = plt.subplots(1, 1, figsize=(8, 8))
ax.scatter(x, y)
ax.use_sticky_edges = True
_, xmax = plt.gca().get_xlim()
ax.axvspan(0.5, xmax=xmax, color="#97999B", zorder=-1)
plt.show()

** Result:**

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • 2
    `ax.set_xlim(right=xmax)`? – BigBen May 22 '23 at 13:10
  • 1
    Thank you @BigBen , I see your point. My MWE wasn't specific enough. I want the axvspan always reaching the axis bounding box depending on the data. – Philipp Weder May 22 '23 at 13:14
  • 2
    This is [the answer](https://stackoverflow.com/questions/42045767/how-can-i-change-the-x-axis-so-there-is-no-white-space) you need. `ax.margins(x=0)` – r-beginners May 22 '23 at 13:16
  • ... except this also changes the left x-margin, which may be undesirable. – BigBen May 22 '23 at 13:16
  • Also `fig, ax = plt.subplots(1, 1, figsize=(8, 8), tight_layout=True)` – Trenton McKinney May 22 '23 at 19:06
  • Does this answer your question? [Matplotlib: make objects ignored by axis autoscaling](https://stackoverflow.com/questions/66805192/matplotlib-make-objects-ignored-by-axis-autoscaling) – Sam Mason May 22 '23 at 20:20
  • specifically, a call to `ax.add_artist(plt.Rectangle((0.5, -1), 1, 3, facecolor="#97999B", zorder=-1))` seems to work well with your example, but has more hard-coded values that might not work if you want them autocalculated based on things you add to the plot later – Sam Mason May 22 '23 at 20:23

0 Answers0