【发布时间】:2021-01-18 06:34:00
【问题描述】:
我编写了一个代码来打开多个.ivc 文件,清理数据并在单个图中绘制图形。不幸的是,即使我选择了多个文件,我的代码仍在从一个文件中绘制数据。
我的代码是
import pandas as pd
import matplotlib.image as image
import numpy as np
import tkinter as tk
import matplotlib.ticker as ticker
from tkinter import filedialog
import matplotlib.pyplot as plt
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
files1 = filedialog.askopenfilename(multiple=True)
files = root.tk.splitlist(files1)
List = list(files)
%gui tk
Str=''.join(List)
fname = Str.split('.')[0]
dic={}
for i,file in enumerate(List):
d = open(file)
for ln in d.readlines():
ln = ln.strip()
if ln.startswith('Volt') or \
ln.startswith('Ref ') or \
ln.startswith('Cur') or \
ln.startswith('Raw ') or \
ln.startswith('WPVS '):
hdr=[h.strip() for h in ln.split(':')[:2]] # store headers
dic[hdr[0]], dic[hdr[1]] = [], []
elif dic != {} and ln != '':
data = ln.split() # split data
dic[hdr[0]].append(data[0]) # add to data lists
dic[hdr[1]].append(data[1])# trim whitespace
mxlen = 0
for k in dic:
if len(dic[k]) > mxlen:
mxlen = len(dic[k])
#print('Max column length',mxlen)
# fill in -1 to make columns same length
for k in dic:
dic[k].extend([0]*(mxlen-len(dic[k])))
df = pd.DataFrame(dic)
df = df.apply(pd.to_numeric)
df['Power'] = df['Voltage']*df['Current']
df = df.replace(0, np.nan)
df = df.dropna(how='all', axis=0)
#plotting
fig = plt.figure(figsize=(30, 20))
ax = fig.add_subplot()
ax1 =ax.twinx()
ax.grid(True,axis='both')
#ax.set(xlabel="Voltage", ylabel="Current", title="IV Curve")
ax.set_xlabel("Voltage [V]",fontsize = 20)
ax1.set_xlabel("Voltage [V]",fontsize = 20)
ax.set_ylabel("Current [I]",fontsize = 20)
ax1.set_ylabel("Power [W]",fontsize = 20)
ax1.spines['right'].set_color('red')
ax.spines['left'].set_color('red')
ax.get_shared_x_axes().join(ax, ax1)
#ax.set_title("IV/PV Curve Plot",fontweight ='bold', fontsize = 30, color='blue')
ax1.tick_params(axis='both', which='both', labelsize=20)
ax.set_ylim (0,4) #adjust the current limits
ax.set_xlim (0,70) #adjust the voltage limits
ax.tick_params(axis='both', which='both', labelsize=20)
ax1.set_ylim (0,150) #adjust the power limits
ax1.set_xlim (0,70) #adjust the voltage limits
ax.plot('Voltage', 'Current', data=df, linewidth=4, label='IV curve')
ax1.plot('Voltage', 'Power', data=df, linewidth=4, color='r', label ='PV Curve')
ax.legend( loc='upper right',fontsize=20)
ax1.legend(loc='lower right',fontsize=20)
#pmax and Vmax
Pmax = df["Power"].max()
maxrow = df[df['Power']==Pmax]
Voltage = maxrow['Voltage'].iloc[0]
Current = maxrow['Current'].iloc[0]
xmax1 =(Voltage/70)
xmax2 =(Current/4)
ax.axhline(y=Current, xmin=0, xmax =xmax1,linewidth=4, color ='g',linestyle='--',)
ax.axvline(x=Voltage, ymin=0, ymax =xmax2, linewidth=4, color='g', linestyle='--')
#img = image.imread("/home/hebin/Desktop/PV/Mitsui/Flasher/logo.png")
#plt.figimage(img, 1380, 1150, alpha=1)
plt.tight_layout()
#plt.savefig(fname + ".png")
print(f'IV: {file}')
示例数据文件的链接:
https://drive.google.com/drive/folders/1sL2-CwCGeGm0-fvcpzMVzgFnYzN3wzVb?usp=sharing
谁能帮我解决这个问题
【问题讨论】:
标签: python pandas dataframe csv matplotlib