matplotlib 未显示Python散点图,仅更新比例

vyu0f0g1  于 2023-11-22  发布在  Python
关注(0)|答案(1)|浏览(107)

我尝试使用另一个简单代码的相同结构来创建python中的实时更新图。
这是一个简单的,完美的工作,更新相同的数字。

import matplotlib.pyplot as plt
import numpy as np
import time

# Create initial data
x = [15.1, 15.1, 15.1, 15.1, 15.1, 15.1, 15.1]
y =[10.3, 10.8, 11.3, 11.8, 12.3, 12.8, 13.3]
values = [31.628036009300377, 32.7041794935823, 32.41961219746959, 32.2074371367232, 32.69759838127627, 33.06824662635184, 32.44804260263164]  # Array of values for the colormap

plt.ion()  # Turn on interactive mode
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=values, cmap='viridis', vmin=0, vmax=1)
ax.set_title("Dynamic Scatter Plot")

# Simulate continuous data updates in a loop
while True:
    # Generate new random data and values
    x = np.random.rand(50)
    y = np.random.rand(50)
    values = np.random.rand(50)

    # Update the scatter plot data and colors
    scatter.set_offsets(np.column_stack((x, y)))
    scatter.set_array(values)

    # Redraw the updated plot
    fig.canvas.draw()

    # Pause for a short duration to make the update visible
    plt.pause(0.1)

# Optionally, turn off interactive mode when you're done
plt.ioff()
plt.show()

字符串
这是我的代码,它没有显示图中的点。虽然,如果我取消注解while循环中的4行,那么点会显示出来,但它会在每个while循环中创建另一个图。

import time, os,my_module
from my_module import getData,init_list_of_objects, plot
from statistics  import mean, stdev
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

global DATA
j=0
size=400 #(autodefine it using list dir somehow)

filename,x,y,z,labels,date=[],[],[],[],[],[]
average, deviation=[],[]

folder_path = "data"  # Relative folder path
  
def Statistics(data): #given an array with data, it does the maths for average and deviation
    average.append(mean(data))
    deviation.append(stdev(data))
    #print('\nAverage and deviation calculated.')

signal= init_list_of_objects(size) #defines a matrix for the signal 'cuz each file has an array of data--> I need a matrix for all the files
DATA=dict(filename=filename,x=x,y=y,signal=signal,labels=labels, date=date) #dictionary with all the data and info related to the excel files

seen_files = set()

plt.ion()  # Turn on interactive mode
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=z, cmap='cool')
ax.set_title("Dynamic Scatter Plot")
# Create a color bar
cbar = fig.colorbar(scatter, ax=ax)

while True:
    new_files = [f for f in os.listdir(folder_path) if f.endswith('.xls') and f not in seen_files]
    for new_file in new_files:
        print(f"\n------------------------\nNew file added: {new_file},\n\t getting data...")
        getData(folder_path,new_file,DATA,j) 
        Statistics(DATA['signal'][j])
        
        x,y,z=plot(DATA,average)
        
        # Update the scatter plot data and colors
        scatter.set_offsets(np.column_stack((x, y)))
        scatter.set_array(z)

        # Update the color bar limits
        scatter.set_clim(vmin=min(z), vmax=max(z))

        # Redraw the updated plot
        fig.canvas.draw()
        fig.canvas.flush_events() 

        # Pause for a short duration to make the update visible
        plt.pause(1)
        
        '''fig, ax = plt.subplots()
        scatter = ax.scatter(x, y, c=z, cmap='cool')
        ax.set_title("Dynamic Scatter Plot")
        cbar = fig.colorbar(scatter, ax=ax)'''

           
        seen_files.add(new_file)
        j+=1
    time.sleep(10)  # Check every 10 seconds (adjust as needed)

plt.show()


为什么同样的逻辑在我的案例中失败了?
我也试着在代码plt.show()plt.clf的不同部分放置,但是没有改变。数组x,y和z由while循环填充,如果我取消注解这4行,我在每个while循环都能正确地得到图。我只是不明白为什么我不能更新第一个。

eqzww0vc

eqzww0vc1#

我已经修复了bug。
下面是代码:

import time, os,my_module
from my_module import getData,init_list_of_objects, plot
from statistics  import mean, stdev
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

global DATA
j=0
size=400 #(autodefine it using list dir somehow)

filename,x,y,z,labels,date=[],[],[],[],[],[]
average, deviation=[],[]

folder_path = "data"  # Relative folder path
  
def Statistics(data): #given an array with data, it does the maths for average and deviation
    average.append(mean(data))
    deviation.append(stdev(data))
    #print('\nAverage and deviation calculated.')

signal= init_list_of_objects(size) #defines a matrix for the signal 'cuz each file has an array of data--> I need a matrix for all the files
DATA=dict(filename=filename,x=x,y=y,signal=signal,labels=labels, date=date) #dictionary with all the data and info related to the excel files

seen_files = set()

plt.ion()  # Turn on interactive mode
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=z, cmap='cool')
ax.set_title("Dynamic Scatter Plot")
ax.set_ylabel('y (mm)')
ax.set_xlabel('x (mm)')

# Create a color bar
cbar = fig.colorbar(scatter, ax=ax)

while True:
    new_files = [f for f in os.listdir(folder_path) if f.endswith('.xls') and f not in seen_files]
    for new_file in new_files:
        print(f"\n------------------------\nNew file added: {new_file},\n\t getting data...")
        getData(folder_path,new_file,DATA,j) 
        Statistics(DATA['signal'][j])
        
        x,y,z=plot(DATA,average)
        
        # Update the color bar limits
        scatter.set_clim(vmin=min(z), vmax=max(z))

        # Redraw the updated plot
        fig.canvas.draw()
        fig.canvas.flush_events() 
        # Update the scatter plot data and colors
        scatter = ax.scatter(x, y, c=z, cmap='cool')
   
        # Pause for a short duration to make the update visible
        plt.pause(1)
        plt.show()

        
        seen_files.add(new_file)
        j+=1
    time.sleep(10)  # Check every 10 seconds (adjust as needed)

字符串
它略有不同,但本质上是相同的代码。我的问题是我使用的编辑器(Spyder),由于某种原因,不能正常工作。我用一个简单的python IDLE运行代码,错误就消失了!
我希望它会帮助别人!

相关问题