Home >Backend Development >Python Tutorial >How to Correctly Set Y-Axis Limits in Matplotlib?

How to Correctly Set Y-Axis Limits in Matplotlib?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 15:33:13691browse

How to Correctly Set Y-Axis Limits in Matplotlib?

Setting Axis Limits in Matplotlib

Question:

Faced with an unsuccessful attempt to set the y-axis limits on a Matplotlib plot, a user seeks guidance on how to achieve the desired limits using the following code:

import matplotlib.pyplot as plt

plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
aPlot = plt.subplot(321, axisbg = 'w', title = "Year 1")
ax.append(aPlot)
plt.plot(paramValues,plotDataPrice[0], color = '#340B8C', 
     marker = 'o', ms = 5, mfc = '#EB1717')
plt.xticks(paramValues)
plt.ylabel('Average Price')
plt.xlabel('Mark-up')
plt.grid(True)
plt.ylim((25,250))

Despite setting plt.ylim((25,250)), the y-axis limits default to 20 and 200. How can the limits be adjusted to the intended 20 and 250?

Answer:

To set the axis limits in Matplotlib, one needs to access the current axis using plt.gca(). Once the current axis is obtained, the limits can be set using the set_ylim() method. The following code snippet demonstrates this:

ax = plt.gca()
ax.set_ylim([20, 250])

By implementing this modification, the y-axis limits will be successfully adjusted to the desired 20 and 250.

The above is the detailed content of How to Correctly Set Y-Axis Limits in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn