如何设置子图轴范围

发布于 2024-09-02 00:33:58 字数 947 浏览 9 评论 0原文

如何将第二个子图的 y 轴范围设置为 [0,1000] ? 我的数据(文本文件中的一列)的 FFT 图会产生(inf.?)峰值,因此实际数据不可见。

pylab.ylim([0,1000])

不幸的是,没有效果。这是整个脚本:

# based on http://www.swharden.com/blog/2009-01-21-signal-filtering-with-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.axis([None,None,0,1000])
pylab.ylim([0,1000])
pylab.plot(abs(fft))

pylab.savefig("SIG.png",dpi=200)
pylab.show()

其他改进也值得赞赏!

How can I set the y axis range of the second subplot to e.g. [0,1000] ?
The FFT plot of my data (a column in a text file) results in a (inf.?) spike so that the actual data is not visible.

pylab.ylim([0,1000])

has no effect, unfortunately. This is the whole script:

# based on http://www.swharden.com/blog/2009-01-21-signal-filtering-with-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.axis([None,None,0,1000])
pylab.ylim([0,1000])
pylab.plot(abs(fft))

pylab.savefig("SIG.png",dpi=200)
pylab.show()

Other improvements are also appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

寒江雪… 2024-09-09 00:33:58

您有 pylab.ylim

pylab.ylim([0,1000])

注意:该命令必须在绘图后执行!

2021 年更新
由于 matplotlib 现在强烈建议不要使用 pylab ,你应该使用 pyplot:

from matplotlib import pyplot as plt
plt.ylim(0, 100) 
#corresponding function for the x-axis
plt.xlim(1, 1000)

You have pylab.ylim:

pylab.ylim([0,1000])

Note: The command has to be executed after the plot!

Update 2021
Since the use of pylab is now strongly discouraged by matplotlib, you should instead use pyplot:

from matplotlib import pyplot as plt
plt.ylim(0, 100) 
#corresponding function for the x-axis
plt.xlim(1, 1000)
那伤。 2024-09-09 00:33:58

使用 axes 对象 是一个很好的方法。如果您想与多个图形和子图交互,它会很有帮助。要直接添加和操作轴对象:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,9))

signal_axes = fig.add_subplot(211)
signal_axes.plot(xs,rawsignal)

fft_axes = fig.add_subplot(212)
fft_axes.set_title("FFT")
fft_axes.set_autoscaley_on(False)
fft_axes.set_ylim([0,1000])
fft = scipy.fft(rawsignal)
fft_axes.plot(abs(fft))

plt.show()

Using axes objects is a great approach for this. It helps if you want to interact with multiple figures and sub-plots. To add and manipulate the axes objects directly:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,9))

signal_axes = fig.add_subplot(211)
signal_axes.plot(xs,rawsignal)

fft_axes = fig.add_subplot(212)
fft_axes.set_title("FFT")
fft_axes.set_autoscaley_on(False)
fft_axes.set_ylim([0,1000])
fft = scipy.fft(rawsignal)
fft_axes.plot(abs(fft))

plt.show()
只想待在家 2024-09-09 00:33:58

有时您确实想在绘制数据之前设置轴限制。在这种情况下,您可以设置 Axes 或 AxesSubplot 对象的“自动缩放”功能。感兴趣的函数是 set_autoscale_onset_autoscalex_onset_autoscaley_on

在您的情况下,您希望冻结 y 轴的限制,但允许 x 轴扩展以容纳您的数据。因此,您需要将 autoscaley_on 属性更改为 False。以下是代码中 FFT 子图片段的修改版本:

fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))

Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes or AxesSubplot object. The functions of interest are set_autoscale_on, set_autoscalex_on, and set_autoscaley_on.

In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on property to False. Here is a modified version of the FFT subplot snippet from your code:

fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))
笑饮青盏花 2024-09-09 00:33:58

如果您有多个子图,即

fig, ax = plt.subplots(4, 2)

您可以对所有子图使用相同的 y 限制。它从第一个图中获取 y 轴的限制。

plt.setp(ax, ylim=ax[0,0].get_ylim())

If you have multiple subplots, i.e.

fig, ax = plt.subplots(4, 2)

You can use the same y limits for all of them. It gets limits of y ax from first plot.

plt.setp(ax, ylim=ax[0,0].get_ylim())
饭团 2024-09-09 00:33:58

也可以在向现有图形实例添加子图时设置ylim/xlimplt.subplot承认ylim = 参数)。

import numpy as np
import matplotlib.pyplot as plt

xs = np.arange(1000)                             # sample data
rawsignal = np.random.rand(1000)
fft = np.fft.fft(rawsignal)

plt.figure(figsize=(9,6))                        # create figure
plt.subplots_adjust(hspace=0.4)

plt.subplot(2, 1, 1, title='Signal')             # first subplot
plt.plot(xs, rawsignal)

plt.subplot(2, 1, 2, title='FFT', ylim=(0,100))  # second subplot
#                                 ^^^^^  <---- set ylim here
plt.plot(abs(fft));

话又说回来,使用面向对象的接口更简洁、更清晰。 Axes 实例定义 set() 方法,可用于设置包括 y-limit/title 等在内的一系列属性。

fig, (ax1, ax2) = plt.subplots(2, figsize=(9,6))
ax1.plot(xs, rawsignal)                # plot rawsignal in the first Axes
ax1.set(title='Signal')                # set the title of the first Axes
ax2.plot(abs(fft))                     # plot FFT in the second Axes
ax2.set(ylim=(0, 100), title='FFT');   # set title and y-limit of the second Axes

两组代码产生相同的以下输出。

结果

It's also possible to set ylim/xlim at the time of adding a subplot to the existing figure instance (plt.subplot admits ylim= argument).

import numpy as np
import matplotlib.pyplot as plt

xs = np.arange(1000)                             # sample data
rawsignal = np.random.rand(1000)
fft = np.fft.fft(rawsignal)

plt.figure(figsize=(9,6))                        # create figure
plt.subplots_adjust(hspace=0.4)

plt.subplot(2, 1, 1, title='Signal')             # first subplot
plt.plot(xs, rawsignal)

plt.subplot(2, 1, 2, title='FFT', ylim=(0,100))  # second subplot
#                                 ^^^^^  <---- set ylim here
plt.plot(abs(fft));

Then again, using the object-oriented interface is less verbose and clearer. Axes instances define set() method which can be used to set a whole host of properties including y-limit/title etc.

fig, (ax1, ax2) = plt.subplots(2, figsize=(9,6))
ax1.plot(xs, rawsignal)                # plot rawsignal in the first Axes
ax1.set(title='Signal')                # set the title of the first Axes
ax2.plot(abs(fft))                     # plot FFT in the second Axes
ax2.set(ylim=(0, 100), title='FFT');   # set title and y-limit of the second Axes

Both sets of codes produce the same following output.

result

緦唸λ蓇 2024-09-09 00:33:58

如果您知道所需的确切轴,则

pylab.ylim([0,1000])

工作方式如前面所回答。但是,如果您想要一个更灵活的轴来适应您的确切数据,就像我发现这个问题时所做的那样,那么将轴限制设置为数据集的长度。如果您的数据集是 fft 如问题所示,请在绘图命令后添加以下内容:

length = (len(fft))
pylab.ylim([0,长度])

If you know the exact axis you want, then

pylab.ylim([0,1000])

works as answered previously. But if you want a more flexible axis to fit your exact data, as I did when I found this question, then set axis limit to be the length of your dataset. If your dataset is fft as in the question, then add this after your plot command:

length = (len(fft))
pylab.ylim([0,length])

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文