Pyplot – automatically setting x axis range to min, max x values passed to plotting function

Question:

I’m creating a plot with a method similar to the following:

import pyplot as plt

for x_list in x_list_of_lists:
   plt.plot(y_list, x_list)

plt.show()

The range of the x axis seems to get set to the range of the first list of x values that is passed to plt.plot(). Is there a way to have pyplot automatically set the lower limit of the x axis to the lowest value in all of the x_list variables passed to it (plus a bit of leeway), and to have it do the same for the upper limit, using the highest x value passed to plot (plus a bit of leeway)? Thank you.

Asked By: Lamps1829

||

Answers:

Confusingly, your y_list contains the values being plotted along the x-axis. If you want matplotlib to use values from x_list as x-coordinates, then you should call

plt.plot(x_list, y_list)

Maybe this is the root of your problem.
By default matplotlib sets the x and y limits big enough to include all the data plotted.

So with this change, matplotlib will now be using x_list as x-coordinates, and will automatically set the limits of the x-axis to be wide enough to display all the x-coordinates specified in x_list_of_lists.


However, if you wish to adjust the x limits, you could use the plt.xlim function.

So, to set the lower limit of the x-axis to the lowest value in all of the x_list variables (and similarly for the upper limit), you’d do this:

xmin = min([min(x_list) for x_list in x_list_of_lists])-delta
xmax = max([max(x_list) for x_list in x_list_of_lists])+delta
plt.xlim(xmin, xmax)

Make sure you place this after all the calls to plt.plot and (of course) before plt.show().

Answered By: unutbu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.