If you work in the field of data science you might have to draw a lot of plots using either Matplotlib or Seaborn. In this blog post, you will learn how to set a limit to the y-axis values in Matplotlib.
We will start by loading the Boston household data and process the data to visualize the median price of the house.
- Load the data
- Import Libraries and plot data points
- Set the y-axis limit
Load the data
Let us begin by loading the data using the pandas library
import matplotlib.pyplot as plt import pandas as pd data = pd.read_csv('sample_data/california_housing_test.csv')
Import Libraries and Plot Data Points
house_values = data['median_house_value'].values house_values = sorted(house_values)
We now have extracted the median_hoise_value
column and sorted the values in ascending order. Let us now being plotting the data
Set the y-axis Limit
paramValues = range(len(house_values)) plt.figure(figsize=(8.5,11)) plt.plot(paramValues,house_values) plt.title('Median house price') plt.ylabel('Median Price') plt.xlabel('Range') plt.grid(True) plt.show()
Change y-axis Limit
paramValues = range(len(house_values)) plt.figure(figsize=(8.5,11)) plt.plot(paramValues,house_values) plt.title('Median house price') plt.ylabel('Median Price') plt.xlabel('Range') plt.grid(True) plt.ylim((None,400000)) plt.show()
By using the plt.ylim()
function we can change the limit of the y-axis. In the above example setting the second parameter to 400000 we have to change the maximum value of the y axis. Similarly, we can change the minimum value of the y-axis by changing the first argument in the plt.ylim()
function
Summary
In this blog post you have learned how to set the y-axis limit in matpltotlib
.Β I hope you found the post informative.