图形的下拉菜单

Drop down menu for the graph

我是 python 的新手,我正在尝试为此图表制作一个下拉菜单,显示 day.The 数据从 csv 文件导入的不同时间的温度。下面是代码:

import csv

import matplotlib.pyplot as plt 
 
x=[]
 
y=[] 

z=[]
 
w=[] 

class grafice_statice():

    def run(self):
        with open('temperatura.csv', 'r') as csvfile:
            date = csv.reader(csvfile, delimiter=',')
            for row in date:
                try:
                    y.append(float(row[0]))
                    z.append(float(row[1]))
                    w.append(float(row[2]))
                    x.append(row[3])
                except Exception as e:
                    pass

        
        plt.figure(1)
        plt.plot(x,z, color='g', linestyle='dotted', marker='o', label='Temp 2(°C)!')
        plt.plot(x,y, color='m', linestyle='solid', marker='P', label='Temp 1(°C)!')
        plt.plot(x,w, color='r', linestyle='dashdot', marker='D', label='Temp 3(°C)!')

        plt.xlabel('Timpul')
        plt.ylabel('Temperatura(°C)')
        plt.title('Temperatura in functie de timp', fontsize = 18)
        plt.legend()

        plt.xticks([0,50,99])
        plt.ylim((-5,5))
        plt.show()
             
    grafice_stat=grafice_statice()
    grafice_stat.run()

我该怎么做?

如果我对你的问题的理解正确,你是在尝试设置一个下拉菜单让用户选择要显示的温度图。一种方法是使用 ipywidgets Dropdown 函数。有关它的更多信息,请参见 here.

您可以在下面找到一个示例,其中我创建了 3 个随机温度矢量(因为我无法访问您的数据)。它们存储在列表 temp 中。然后,我让用户通过 dropdown=widgets.Dropdown(options=[('Temp1', 0), ('Temp2', 1), ('Temp3', 2)],value=0,description='Temp') 行的下拉菜单选择要绘制的温度矢量。一旦用户选择,它会通过on_change(change)函数自动更新图形。

因此,总体代码如下所示:

import ipywidgets as widgets
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output

def t_temp(N_points):
  temp_min=-20
  temp_max=40
  temp=np.random.choice(np.arange(temp_min,temp_max),size=N_points)
  return temp 

colors=['tab:blue','tab:orange','tab:green']
N_points=100
t=1+np.arange(N_points)
N_temp_types=3
temp=[]
[temp.append(t_temp(N_points)) for i in range(N_temp_types)]

dropdown=widgets.Dropdown(options=[('Temp1', 0), ('Temp2', 1), ('Temp3', 2)],value=0,description='Temp')
plt.plot(t,temp[int(dropdown.value)],lw=2,color=colors[int(dropdown.value)],label='Temp '+ str(int(dropdown.value)+1))
plt.legend()

def on_change(change):
    if change['type'] == 'change' and change['name'] == 'value':
        clear_output()
        display(dropdown)
        plt.plot(t,temp[int(dropdown.value)],lw=2,color=colors[int(dropdown.value)],label='Temp '+ str(int(dropdown.value)+1))
        plt.legend()
dropdown.observe(on_change)

display(dropdown)

并且输出给出:

选择“临时 1”时:

选择“温度 2”时: