如何在多个图动画中迭代matplotlib中的颜色

发布于 2025-01-25 14:36:35 字数 2830 浏览 3 评论 0原文

我正在尝试从仪器中绘制电流电压采集,但要用于不同的温度。我需要保持结构的呈现,但我想为每个温度带有1个均匀颜色的图,然后在下一个温度上更改颜色,以便我可以识别不同的情节并阅读他们的传说(温度)。现在我得到了动画,但我无法迭代温度和颜色。谢谢

import random
import csv
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd

class IV_SWEEP():
    def __init__(self):
        self.IV_sweep()

    def init_instrument(self):
        #######settings
        self.data_points = 10  # number of steps in the sweep
        self.max_current = 0.001
        self.min_current = -self.max_current
                            
    def measurement(self):
        # Allocate arrays to store the measurement results
        currents = np.linspace(self.min_current, self.max_current, num=self.data_points)
        voltages = np.zeros_like(currents)
        temp_list = [300, 310, 320]  # want to plot a curve for each of this temperature
        for i in range(self.data_points):
            voltages[i] = random.random() + currents[i]
            now = datetime.now()
            self.record_csv(now, currents[i], voltages[i])
            self.animate()
            self.plot() # i am calling the plot method separately but dont know how to iterate the label so the color and legend is changed per temp
            plt.pause(3)      
        self.plot_enable = True

    def IV_sweep(self):
        self.xdata = []   
        self.ydata = []  
        self.init_instrument()
        self.measurement()
           
    def animate(self):
        data = pd.read_csv("test.csv")
        self.xdata = data["Voltage (V)"]
        self.ydata = data["Current (A)"]
              
    def plot(self):
        plt.gcf()
        temp_list = [300, 310, 320]
        labels = temp_list
        # for lab in labels:
        plt.scatter(self.xdata, self.ydata, label=temp_list)  # need to add a different lab for each temperature scan
        plt.xlabel('Voltage (V)')
        plt.ylabel('Current (mA)')
        # plt.title("IV sweep at {} K".format(temp_list[i]))
        plt.title("IV sweep at temperature xx")  # call the temperature so it s printed as legend
        # plt.legend(loc='best')
        plt.tight_layout()
        return

    def record_csv(filename,timestamp, currents, voltages):
        filename = "test.csv"
        with open(filename, 'a', newline='') as csvfile:
            header = ["Timestamp", "Current (A)", "Voltage (V)", "Voltage stdv (V)"]
            writer = csv.DictWriter(csvfile, fieldnames=header)
            if csvfile.tell() == 0:
                writer.writeheader()
            writer.writerow(
                {
                    "Timestamp": timestamp,
                    "Current (A)": currents,
                    "Voltage (V)": voltages,
                }
            )
        csvfile.close()

IV_SWEEP()

i am trying to plot an current-voltage acquisition from an instrument but for different temperatures. I need to keep the structure as presented but i would like to have for each temperature get the plot in 1 uniform color then for the next temperature the color is changed so i can identify different plot and read their legend (the temperature). right now i get the animation but i cannot iterate on temperatures and colors. thanks

import random
import csv
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd

class IV_SWEEP():
    def __init__(self):
        self.IV_sweep()

    def init_instrument(self):
        #######settings
        self.data_points = 10  # number of steps in the sweep
        self.max_current = 0.001
        self.min_current = -self.max_current
                            
    def measurement(self):
        # Allocate arrays to store the measurement results
        currents = np.linspace(self.min_current, self.max_current, num=self.data_points)
        voltages = np.zeros_like(currents)
        temp_list = [300, 310, 320]  # want to plot a curve for each of this temperature
        for i in range(self.data_points):
            voltages[i] = random.random() + currents[i]
            now = datetime.now()
            self.record_csv(now, currents[i], voltages[i])
            self.animate()
            self.plot() # i am calling the plot method separately but dont know how to iterate the label so the color and legend is changed per temp
            plt.pause(3)      
        self.plot_enable = True

    def IV_sweep(self):
        self.xdata = []   
        self.ydata = []  
        self.init_instrument()
        self.measurement()
           
    def animate(self):
        data = pd.read_csv("test.csv")
        self.xdata = data["Voltage (V)"]
        self.ydata = data["Current (A)"]
              
    def plot(self):
        plt.gcf()
        temp_list = [300, 310, 320]
        labels = temp_list
        # for lab in labels:
        plt.scatter(self.xdata, self.ydata, label=temp_list)  # need to add a different lab for each temperature scan
        plt.xlabel('Voltage (V)')
        plt.ylabel('Current (mA)')
        # plt.title("IV sweep at {} K".format(temp_list[i]))
        plt.title("IV sweep at temperature xx")  # call the temperature so it s printed as legend
        # plt.legend(loc='best')
        plt.tight_layout()
        return

    def record_csv(filename,timestamp, currents, voltages):
        filename = "test.csv"
        with open(filename, 'a', newline='') as csvfile:
            header = ["Timestamp", "Current (A)", "Voltage (V)", "Voltage stdv (V)"]
            writer = csv.DictWriter(csvfile, fieldnames=header)
            if csvfile.tell() == 0:
                writer.writeheader()
            writer.writerow(
                {
                    "Timestamp": timestamp,
                    "Current (A)": currents,
                    "Voltage (V)": voltages,
                }
            )
        csvfile.close()

IV_SWEEP()

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

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

发布评论

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

评论(1

尘曦 2025-02-01 14:36:35
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random 

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


def main(i):

    # Actual parameters
    # A0 = 10 
    A0 = 2
    K0 = [1, 3, 5] 
    C0 = 5     
    # Generate some data based on these
    tmin, tmax = 0, 0.5
    num = 20
    t = []
    y = []
    for K in K0:  #would like to scan on K and plot each curve with a different color
        t = np.linspace(tmin, tmax, num)
        y = model_func(t, A0, K, C0)
        ax1.scatter(t,y, label = K) # would like to have as a legend each K
        ax1.legend(loc="upper left")

def model_func(t, A, K, C):   
        return A * np.exp(K * t) + C

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

plt.show()

结果:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random 

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


def main(i):

    # Actual parameters
    # A0 = 10 
    A0 = 2
    K0 = [1, 3, 5] 
    C0 = 5     
    # Generate some data based on these
    tmin, tmax = 0, 0.5
    num = 20
    t = []
    y = []
    for K in K0:  #would like to scan on K and plot each curve with a different color
        t = np.linspace(tmin, tmax, num)
        y = model_func(t, A0, K, C0)
        ax1.scatter(t,y, label = K) # would like to have as a legend each K
        ax1.legend(loc="upper left")

def model_func(t, A, K, C):   
        return A * np.exp(K * t) + C

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

plt.show()

Result:

enter image description here

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