<jupyter_start><jupyter_text>Spectra of All Precursors in (1 Graph per Timepoint)<jupyter_code>class SpectraByPrecursor():
    
    def __init__(self, file):
        self.file = file
        
    def get_spectra(self):
        df = pd.read_excel(self.file, header=None)
        df.replace('OVRFLW', 4.0, inplace=True)
        
        # names
        ph_list = ['ph 6', 'ph 6_chloride', 'ph 7', 'ph 7_chloride', 
                   'ph 8', 'ph 8_chloride', 'GA in Water', 'Water (Blank)']
        std_list = [each + ' std' for each in ph_list]
        mean_list = [each + ' mean' for each in ph_list]
        samples = ['pH 6', 'pH 6 + chloride', 'pH 7', 'pH 7 + chloride', 
                   'pH 8', 'pH 8 + chloride', 'GA in Water', 'Water (Blank)']
        sample_dict = dict(zip(mean_list, samples))
        
        # data manipulation
        combined_list = []
        for i in range(len(std_list)):
            combined_list.append(mean_list[i])
            combined_list.append(std_list[i])

        wavelengths = np.arange(300,701,10)
        frames = []
        for i in range(len(wavelengths)):
            starter = 26 + i*12
            ender = 34 + i*12
            frame = df.iloc[starter:ender, 2:5]
            frame.columns = ['t1', 't2', 't3']
            frame.index = ph_list
            frames.append(frame)

        means = []
        for i in range(len(frames)):
            df1 = frames[i].mean(axis='columns')
            df1.index = mean_list
            means.append(df1)

        stdevs = []
        for i in range(len(frames)):
            df1 = frames[i].std(axis='columns')
            df1.index = std_list
            stdevs.append(df1)

        mean_df = pd.DataFrame(means, index=wavelengths)
        std_df = pd.DataFrame(stdevs, index=wavelengths)

        compiled_df = pd.concat([mean_df, std_df], axis='columns')
        compiled_df = compiled_df[combined_list]
        
        return compiled_df
    
    def get_plot(self, purpose='plot'):
        
        def _return_legend():
            return ax.legend(prop={'size':12}, loc=(1.04,0))

        def _return_none():
            return None

        def _legend_dict(purpose):
            mydict = {'legend':_return_legend,'plot':_return_none}
            return mydict[purpose]()

        x = self.get_spectra().index
        shape_list = 's,s,o,o,^,^,v,v'.split(',')
        color_list = 'k,k,r,r,g,g,b,b'.split(',')
        #color_list = 'black,black,red,red,lime,lime,deepskyblue,deepskyblue'.split(',')
        fill_list = 'k,none,r,none,g,none,b,none'.split(',')
        mew = [0,0.5,0,0.5,0,0.5,0,0.5]
        
        ph_list = ['ph 6', 'ph 6_chloride', 'ph 7', 'ph 7_chloride', 
                   'ph 8', 'ph 8_chloride', 'GA in Water', 'Water (Blank)']
        std_list = [each + ' std' for each in ph_list]
        mean_list = [each + ' mean' for each in ph_list]
        samples = ['pH 6', 'pH 6 + chloride', 'pH 7', 'pH 7 + chloride', 
                   'pH 8', 'pH 8 + chloride', 'GA in Water', 'Water (Blank)']
        sample_dict = dict(zip(mean_list, samples))
        
        compiled_df = self.get_spectra()
        
        fig = plt.figure(figsize=(3.6,3))
        ax = fig.add_subplot(111)
        for i in range(len(mean_list)):
            mean_col = mean_list[i]
            std_col = std_list[i]
            y = compiled_df[mean_col]
            err = compiled_df[std_col]
            fmt = color_list[i]+shape_list[i]
            #ax.plot(x, y, fmt, markerfacecolor=fill_list[i])
            ax.errorbar(x,y, yerr=err, fmt=fmt, markeredgewidth=mew[i],
                        markerfacecolor=fill_list[i],
                        markersize=6.5, label=sample_dict[mean_col])
            #ax.legend(prop={'size':12}, loc=(1.04,0)) #comment-out yet since only 1 legend will be used in the manuscript
        _legend_dict(purpose) # can remove the arg from def and it will scope to arg in outer def
        ax.set_xlabel('Wavelength (nm)', fontsize=11)
        ax.set_ylabel('Absorbance', fontsize=11)
        ax.set_ylim([-0.1,4.3])
        
        x_minor_locator = AutoMinorLocator(2)
        ax.xaxis.set_minor_locator(x_minor_locator)
        
        y_minor_locator = AutoMinorLocator(2)
        ax.yaxis.set_minor_locator(y_minor_locator)
        
        plt.tight_layout()
location = r"C:\codeenv\Thesis\Raw\uv-vis spectra"
filenames = [xlfile for xlfile in os.listdir(location) if xlfile.startswith('GA Buffer')]
files = list(map(lambda x: os.path.join(location, x), filenames))
savelocation = r'C:\codeenv\Thesis\Manuscript\Manuscript proper\Images, tables\regen mpl'

for file in files:
    filename = os.path.splitext(os.path.basename(file))[0]
    spectra = SpectraByPrecursor(file)
    spectra.get_plot() 
    plt.show()
    #plt.savefig(os.path.join(savelocation,filename)+'.tif', dpi=300)
# enable the ax.legend on line 96 in the class definition and run this cell to get a legend
filename = os.path.splitext(os.path.basename(file))[0]
spectra = SpectraByPrecursor(file)
spectra.get_plot('legend') 
plt.show()
#plt.savefig(os.path.join(savelocation,'legend.tif'), dpi=300)<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup