Matplotlib从CSV实时更新条形图

2024-04-24 21:14:27 发布

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

对python来说是个新手,所以任何指导都将不胜感激! 我有一个有名字的CSV。我试着数一数每个叫“亚当”的人,然后把它画在条形图上。当CSV更新时,我希望条形图也能更新。下面是我的代码。你知道吗

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import csv
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
myCount = 0
otherCount = 0
def animate(i):
    with open('test2.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            if row['fName'] == 'Adam':
                myCount +=1
            else:
                otherCount = +=1    
    x = ["Adam","Not Adam"]
    y = [myCount, otherCount]
    ax1.clear()
    ax1.bar(x,y)
ani = animation.FuncAnimation(fig, animate, interval=1000)            
plt.show()

现在它显示了图形的轮廓,但没有显示任何内容。 另外,我从另一个来源获得了动画功能。有没有更有效的方法?你知道吗

好的,我更新了代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import csv
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    myCount = 0
    otherCount = 0
    with open('testcsv.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            if row['fName'] == 'Adam':
                myCount +=1
            else:
                otherCount +=1    
    x = ["Adam","Not Adam"]
    y = [myCount, otherCount]
    ax1.clear()
    ax1.bar(x,y)
ani = animation.FuncAnimation(fig, animate, interval=1000)            
plt.show()

通过测试我知道它正确地抓取了CSV并读取了数据,但是它仍然没有绘制出它。数据如下所示:

fname,lname
Adam,Smith
Adam,Sandler
Adam,Smith
Adam,Sandler
Bruce,Willis
Adam,Smith
James,Harden
Bruce,Wayne

Tags: csvcsvfileimportmatplotlibasfigpltreader
1条回答
网友
1楼 · 发布于 2024-04-24 21:14:27

代码似乎有三个主要问题。前两个与正在使用的计数器有关。最后是数据的命名。你知道吗

  1. otherCount = +=1不是有效的python。你知道吗
  2. 局部递增变量不会全局更改它。因此,在动画函数中定义myCount = 0; otherCount = 0是有意义的,以防您不想显示累积计数。你知道吗
  3. 数据列似乎命名为fname,但索引使用row['fName']。你知道吗

相关问题 更多 >