user7468395
user7468395

Reputation: 1359

What is the name of the matplotlib function that gets executed when initially plotting the data which sets all axes correctly?

When I plot some data with matplotlib without setting any parameters, the data gets plotted with both x and y axis limits set correctly, meaning that all data is shown and no space is wasted (case 1):

import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
x = range(10)

plt.plot(x,'-o',markersize='10')

plt.tight_layout()
plt.show()

Result:

case 1: initial plotting without any limits set

If I set some limits for e. g. the x axis, even using autoscale() does not autoscale the y axis anymore (case 2):

import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
x = range(10)

plt.plot(x,'-o',markersize='10')
plt.autoscale(enable=True,axis='y')
plt.xlim(7.5,11)
plt.tight_layout()
plt.show()

Result:

case 2: using x limits

Question: which function is used internally by matplotlib to determine the limits for both axes and update the plot in case 1?

Background: I want to use this function as a base for reimplementing / extending this functionality for case 2.

Upvotes: 1

Views: 91

Answers (1)

Sheldore
Sheldore

Reputation: 39072

As @ImportanceOfBeingEarnest pointed out in the answer below, there is no such automatized way at the moment. So, in case you are interested in knowing how to rescale your y-axis, one way to do so is by recomputing the corresponding y-values and then reassigning the y-limits using the method specified in this unaccepted answer. I haven't marked this as a duplicate because there are certain different issues in your example:

  • First (major one), you have plotted only x-values. So, to apply the method in the other answer, I had to first get the y-values in an array. This is done using get_ydata()
  • Second, the x-values were changed from range() generator to a NumPy array, as the former does not support indexing.
  • Third, I had to use a variable for the x-limits to be consistent with the function.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)

plt.plot(x,'-o',markersize='10')
x_lims = [7.5, 11]
plt.xlim(x_lims)

ax = plt.gca()
y = ax.lines[0].get_ydata()

def find_nearest(array,value):
    idx = (np.abs(array-value)).argmin()
    return idx

y_low = y[find_nearest(x, x_lims[0])]
y_high = y[find_nearest(x, x_lims[1])]
ax.set_ylim(y_low, y_high)

plt.tight_layout()
plt.show()

enter image description here

Upvotes: 1

Related Questions