Home  >  Article  >  Backend Development  >  How to Adjust Y-Axis Range for Subplots in Python?

How to Adjust Y-Axis Range for Subplots in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 12:41:30632browse

How to Adjust Y-Axis Range for Subplots in Python?

Controlling Subplot Axis Ranges

In visualizing data using subplots, it is often necessary to adjust the axis ranges to enhance readability and emphasize specific features. This article addresses the issue of setting the y-axis range for a specific subplot.

Setting the Y-Axis Range for a Subplot

The y-axis range of a subplot can be modified using the pylab.ylim function. However, it is essential to note that this command takes effect after the plot has been created. Therefore, the correct placement of the command is crucial.

Example Script with Corrected Code

The following script provides an updated version of the code in the original question, with the pylab.ylim command placed correctly:

<code class="python">import numpy, scipy, pylab, random

xs = []
rawsignal = []
with open("test.dat", 'r') as f:
    for line in f:
        if line[0] != '#' and len(line) > 0:
            xs.append( int( line.split()[0] ) )
            rawsignal.append( int( line.split()[1] ) )

h, w = 3, 1
pylab.figure(figsize=(12,9))
pylab.subplots_adjust(hspace=.7)

pylab.subplot(h,w,1)
pylab.title("Signal")
pylab.plot(xs,rawsignal)

pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.plot(abs(fft))
pylab.ylim([0,1000])  # Set the y-axis range for the subplot after plotting

pylab.savefig("SIG.png",dpi=200)
pylab.show()</code>

Additional Improvements

  • Using pyplot instead of pylab: Since the use of pylab is discouraged in matplotlib, it is recommended to use matplotlib.pyplot instead.
  • Using plt.xlim to set the x-axis range: Similar to plt.ylim, plt.xlim can be used to set the x-axis range of the subplot.

The above is the detailed content of How to Adjust Y-Axis Range for Subplots in Python?. 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