So, I'm making a scatter plot, and one of my data columns has lot of negative values. That is my y-axis.
However when I plot it starts my axes from 0. How do I make it start from the actual lowest value?

3 Answers
Use plt.ylim(), along with the built-in min() and max() functions:
import matplotlib.pyplot as plt
x = [38, -21, 37, 54, 10, 10, -40, -37, -24, 53, -10, 45, -32, -37, 12, -29, 18, 5, -45, 19, 48, 48, 27, -10, -17, -15, -25, -44, 41, -8]
y = [31, -43, -3, 18, -48, 4, -54, -34, -42, 13, 31, -4, 17, 3, 16, -30, -23, -27, -9, 13, -40, 13, 0, -41, 5, -26, 16, -9, 40, 16]
plt.ylim(min(y), max(y))
plt.scatter(x, y)
plt.show()
Output:
9 Comments
Red
@Zelix75 Yep :) Just add
plt.xlim(min(x), max(x)) right above the plt.ylim(min(y), max(y)).Zelix75
Worked, however, I had to make min arg of ylim = -10, as otherwise there was no visible difference
Red
@Zelix75 Oh, good! Some people prefer to have padding around the boundaries, so
plt.ylim(min(y), max(y)) caould be plt.ylim(min(y) - 10, max(y) + 10).Zelix75
How do I set a defined scale for my y axis?. Like, I wanna change it to 5 or something
Red
@Zelix75 Use
pot.yticks() with range, third parameter of the range is the scale: plt.yticks(range(min(y), max(y), 5)) |
A quick solution might be matplotlib.pyplot.ylim(). Get your lowest y value and pass it into this to set it as your lowest y axis value.
Something like matplotlib.pyplot.ylim(bottom= np.min(y_array)).
See https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.ylim.html for more details.
