0

When creating a scatterplot using Matplotlib in Python with the undesired regions in red, the plot automatically adds whitespace above or beneath this horizontally colored region (see example). I tried to increase the height of the red area, but the same whitespace appears again.

example

To create the graph, I first plot all values using a for loop. Then, I obtain the max and min value of the y-axis to create the red area. Finally, I show the plot. A minimal code example is shown below.

for col in columns:
  plt.scatter(x_values, y_values)

ymin, ymax = plt.gca().get_ylim()
plt.axhspan(60, 64, facecolor='orange', alpha=0.3)
plt.axhspan(64, ymax, facecolor='red', alpha=0.3)

plt.axhspan(-64, -60, facecolor='orange', alpha=0.3)
plt.axhspan(ymin, -64, facecolor='red', alpha=0.3)

plt.show()
Jeannot
  • 1
  • 1
  • 1
    Most plotting commands (e.g. `plt.axhspan()`) automatically extend the limits to assure everything's visibility, including some margin. You can reapply the limits afterwards with `plt.ylim(ymin,ymax)`. Or you could avoid the margin with `plt.margin(y=0)` – JohanC Oct 19 '22 at 10:05
  • Using `plt.ylim(ymin,ymax)` fixes the problem. Thank you! Using `plt.margin(y=0)` results in the AttributeError _module 'matplotlib.pyplot' has no attribute 'margin'_ – Jeannot Oct 19 '22 at 10:23
  • `plt.margins(y=0)` was missing the plural – JohanC Oct 19 '22 at 11:00

0 Answers0