指数图在python中显示为线性图

2024-10-01 00:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图画出2的指数与2的指数幂的关系,但我一直得到一个线性图,而不是曲线。我不确定我做错了什么

enter image description here

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from random import seed
from random import random
import math

tiktok=0


#Desired style
style.use('dark_background')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)


T= open('live_graphText.txt','w+')
T.truncate(0)
T.close()
test = f=open('live_graphText.txt','w+')
for i in range(10): 
    test.write("%d,%d\n"%(i,math.pow(2,i)))
    tiktok = tiktok+i
test.close()

此外,我正在尝试使用matplotlib.animation中的实时图形动画和我创建的文件。保持自动向文件添加点,但似乎该函数甚至没有被调用。我不确定是在错误的地方调用了它,还是函数没有意义

#This is not being called
def edit(tik):
    global tiktok
    f=open('live_graphText.txt','a+')
    f.write("%d,%d\n"%(tik,math.pow(2,tik)))
    print("HelloWorld")
    tiktok = tiktok +1
    f.close()


def animate(i):
    #Opening the file to read
    graph_data = open('live_graphText.txt','r').read()
    #Split the lines by \n
    lines=graph_data.split('\n')
    xs =[]
    ys =[]
    for line in lines:
        #This if statement ignores any white space at the end of the file
        if len(line)>1:
            x,y = line.split(',')
            xs.append(x)
            ys.append(y)
    #print(xs)
    #print(ys)

    ax1.clear()
    ax1.plot(xs,ys)

#参数为(绘制函数的位置、我们正在绘制的函数、我们要绘制的间隔(以毫秒为单位))

ani = animation.FuncAnimation(fig,animate,interval=1000)


plt.show()
while tiktok<20:
    edit(tiktok)
print(tiktok)
plt.show()

感谢您的帮助


Tags: the函数fromimporttxtlivematplotlibplt