如何使用for循环从二进制数生成十进制数字的动画方波 [英] How do you generate an animated square wave from binary number for the respective decimal number using for loop

查看:113
本文介绍了如何使用for循环从二进制数生成十进制数字的动画方波的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码使用for循环生成方波格式[例如:从0到5].我能够打印相应的二进制值,但不能动态绘制方波.除此之外,我无法在绘制窗口中动态调整x轴的大小.我在Matplotlib动画部分找不到任何合适的代码.有人可以帮我吗?

I am using the following codes to generate the square wave format [Eg: from 0 till 5] using for loop. I am able to print the respective binary values but not able to plot the square wave dynamically.In addition to this I am not able to dynamically resize the x axis in the plot window. I could not find any suitable code at Matplotlib animation section. Could any one help me in this?

import numpy as np
import matplotlib.pyplot as plt

limit=int(raw_input('Enter the value of limit:'))

for x in range(0,limit):
    y=bin(x)[2:]
    data = [int(i) for i in y]
    print data
    xs = np.repeat(range(len(data)),2)
    ys = np.repeat(data, 2)
    xs = xs[1:]
    ys = ys[:-1]
    plt.plot(xs, ys)
    plt.xlim(0,len(data)+0.5)
    plt.ylim(-2, 2)
    plt.grid()
    plt.show()
    #plt.hold(True)
    #plt.pause(0.5)
    plt.clf()

推荐答案

您所说的问题非常含糊,因此我要大胆尝试一下,并假设您要绘制一个一系列等长的二进制代码,使用相同的图形,中间有一些延迟.

Your question as stated is pretty vague so I'm going to I'm going to go out on a limb and assume that what you want is to plot a series of equal length binary codes using the same figure with some delay in between.

因此,这里有两个问题:

So, two problems here:

  1. 生成适当的二进制代码

  1. Generating the appropriate binary codes

依次绘制那些代码

1.生成适当的二进制代码

根据我的合理猜测,您想绘制相同长度的二进制代码.因此,您必须对代码进行零填充,以使它们的长度相同.一种方法是使用python内置的zfill函数.

1. Generating the appropriate binary codes

From what I can reasonably guess, you want to plot binary codes of the same length. So you'll have to zero pad your codes so they are the same length. One way to do this is with python's built in zfill function.

例如

bin(1).zfill(4)

这也使您明白,如果要保持x轴范围恒定,则必须知道要绘制的最大二进制字符串的长度.由于尚不清楚您是否要使用固定长度的字符串,因此我将其保留在此位置.

This also brings light to the fact that you will have to know the length of the largest binary string you want to plot if you want to keep the x-axis range constant. Since it's not clear if you even want constant length strings I'll just leave it at this.

有两种不同的方法可以在matplotlib中创建动画.我发现手动更新数据比当前的animations API灵活一些,而且没有太多错误,因此我将在此处进行说明.我还删减了一些我不清楚的代码.

There are a couple different ways to create animations in matplotlib. I find manually updating data is a little bit more flexible and less buggy than the animations API currently is so I will be doing that here. I've also cut down some parts of the code that were not clear to me.

这是一个简单的实现:

import matplotlib.pyplot as plt
import numpy as np

# Enable interactive plotting
plt.ion()

# Create a figure and axis for plotting on
fig = plt.figure()
ax = fig.add_subplot(111)

# Add the line 'artist' to the plotting axis
# use 'steps' to plot binary codes
line = plt.Line2D((),(),drawstyle='steps-pre')
ax.add_line(line)

# Apply any static formatting to the axis
ax.grid()
ax.set_ylim(-2, 2)
# ...

try:
    limit = int(raw_input('Enter the value of limit:'))
    codelength = int(np.ceil(np.log2(limit)))+1 # see note*
    ax.set_xlim(0,codelength)
    for x in range(0,limit):
        # create your fake data
        y = bin(x)[2:].zfill(codelength)
        data = [int(i) for i in y]
        print data
        xs = range(len(data))

        line.set_data(xs,data)  # Update line data
        fig.canvas.draw()       # Ask to redraw the figure

        # Do a *required* pause to allow figure to redraw
        plt.pause(2)            # delay in seconds between frames
except KeyboardInterrupt:   # allow user to escape with Ctrl+c
    pass
finally:                    # Always clean up!
    plt.close(fig)
    plt.ioff()
    del ax,fig

结果

*注意:我用一个额外的零填充了二进制代码,以使绘图看起来正确.

*Note: I padded the binary codes by an extra zero to get the plot to look right.

这篇关于如何使用for循环从二进制数生成十进制数字的动画方波的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆