Re: [Tutor] Question in regards to loops and matplotlib
]), (1.6,2.5), (-1.,2.5), (-1.,1.3)] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] return Path(verts,codes) def titles_labels(labels, z_range): creates axis labels, title, and legend associating labels to these three specific plots plt.title('UVJ Plot of n2 population at ' + z_range[5]) plt.xlabel('V-J') plt.ylabel('U-V') plt.xlim(0.5, 2.0) plt.ylim(0.5, 2.5) plt.legend([labels[0], labels[1], labels[2]], [Qui-Bulge-Dom, SF-Bulge-Dom, Disk-Dom], 'best', numpoints=1, fontsize='small') def main(): calls total script to create plot to run, simply load csv in the first spot in the np.genfromtxt args and exchange the zbin value to either z1, z2, z3, or z4 fig = plt.figure('UVJ') n2_subset = np.genfromtxt('/Users/ProtonLenny/Documents/Research/Catalog_Data/Catalog_4/n2.csv', dtype=None, names=True, delimiter =,) zbin = z4 z_data = redshift(n2_subset, zbin) qui_data = (quiescence(z_data, zbin))[0] sf_data = (quiescence(z_data, zbin))[1] qui_disk = (disk_vs_bulge(qui_data))[0] qui_bulge = (disk_vs_bulge(qui_data))[1] sf_disk = (disk_vs_bulge(sf_data))[0] sf_bulge = (disk_vs_bulge(sf_data))[1] m_q_disk = make_mass_cuts(qui_disk) m_q_bulge = make_mass_cuts(qui_bulge) m_sf_disk = make_mass_cuts(sf_disk) m_sf_bulge = make_mass_cuts(sf_bulge) legend_labels = plots(m_q_disk, m_q_bulge, m_sf_disk, m_sf_bulge) path = make_hash_region(zbin) titles_labels(legend_labels, zbin) hash_region = patch.PathPatch(path, facecolor='none', lw=1.5, alpha=0.5, hatch='//') ax = fig.add_subplot(111) #subplot for shaded region ax.add_patch(hash_region) plt.show() if __name__ == '__main__': main() On Thu, Aug 8, 2013 at 8:38 AM, Oscar Benjamin oscar.j.benja...@gmail.comwrote: On 1 August 2013 06:21, Zachary Rizer protonle...@gmail.com wrote: So I just started coding, and I'm so glad I chose Python to start me off! I really enjoy the clean layout, easy syntax, and power of the language. I'm doing astronomy research and I just started teaching myself matplotlib along with my general python work. I feel like I'm catching on quick, but I also feel that this particular plot script is a little rough. The plot looks correct, but the code seems really long for what I'm trying to do. So any tricks to make this more efficient would be greatly appreciated! Hi Zachary, You can definitely make this shorter. I can't run your code since you didn't provide any data. It's good to use dummy data in examples posted to mailing lists so that others can run the code. Instead I'll show an example with my own dummy data: #!/usr/bin/env python # # Plot heights and weights of subjects from different groups. from matplotlib import pyplot as plt # Dummy data subjects = [ # Group, height (m), weight (kg), diagnosis {'type': 'patient', 'height': 1.8, 'weight': 90 , 'diag': 'acute' }, {'type': 'patient', 'height': 1.6, 'weight': 85 , 'diag': 'acute' }, {'type': 'patient', 'height': 1.9, 'weight': 120, 'diag': 'chronic'}, {'type': 'patient', 'height': 2.0, 'weight': 110, 'diag': 'chronic'}, {'type': 'control', 'height': 1.7, 'weight': 60 , 'diag': 'N/A'}, {'type': 'control', 'height': 2.1, 'weight': 100, 'diag': 'N/A'}, ] # Have just one place where we define the properties of each group groups = { 'control': { 'indicator': lambda s: s['type'] == 'control', 'color': 'blue', 'marker': '*', 'label':'Controls' }, 'chronic': { 'indicator': lambda s: s['diag'] == 'chronic', 'color': 'magenta', 'marker': 's', 'label':'Chronic patients' }, 'acute' : { 'indicator': lambda s: s['diag'] == 'acute', 'color': 'red', 'marker': 'o', 'label':'Acute patients' }, } # Now we can reuse the same code for every subject for groupdata in groups.values(): groupdata['subjects'] = [] # Distribute the subjects to each group for subject in subjects: for groupdata in groups.values(): isingroup = groupdata['indicator'] if isingroup(subject): groupdata['subjects'].append(subject) break # Now create/format the figure fig = plt.figure(figsize=(6, 5)) ax = fig.add_axes([0.15, 0.15, 0.70, 0.70]) ax.set_xlabel(r'Weight ($kg$)') ax.set_ylabel(r'Height ($m$)') ax.set_title('Height vs. weight by subject group') ax.set_xlim([50, 150]) ax.set_ylim([1.5, 2.2]) # Plot each group separately with its own format settings for group, groupdata in groups.items(): xdata = [s['weight'] for s in groupdata['subjects']] ydata = [s['height'] for s in groupdata
[Tutor] Question in regards to loops and matplotlib
So I just started coding, and I'm so glad I chose Python to start me off! I really enjoy the clean layout, easy syntax, and power of the language. I'm doing astronomy research and I just started teaching myself matplotlib along with my general python work. I feel like I'm catching on quick, but I also feel that this particular plot script is a little rough. The plot looks correct, but the code seems really long for what I'm trying to do. So any tricks to make this more efficient would be greatly appreciated! A little bit about what's going on before I post the script. I'm using np.genfromtext to upload a CSV file of a bunch of astronomy data. I need to break this data down into multiple subsets. 4 mass separated subsets (row['logM']) and each of those is divided into bulge and disk dominated. And for each of those I need to separate quiescent and star forming. So I have a total of 8 star forming subsets and 8 quiescent subsets. And all sixteen different styles of object need a distinct marker on the plot. I hope that with the comments you can see where I divided those up in the code. I did it all with a ton of for loops and if statements filling in a bunch of empty arrays. Hopefully this is enough info to make sense of what I'm going for. My main question is can I shorten this code, especially the for loops, to make it more efficient and clean? Here is the script: # -*- coding: utf-8 -*- #- Zach Rizer #- UVJ plot #- data = n2_qui_flag.csv import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patch from matplotlib.path import Path fig = plt.figure('UVJ') ax = fig.add_subplot(111) #subplot for shaded region ## # - Data uploaded from preliminary TopCat CSV Files data = np.genfromtxt('/Users/ProtonLenny/Documents/Research/Catalog_Data/Catalog_3/n2_qui_flag.csv',\ dtype=None,names=True,delimiter =,) # - Define Quiesent Subset qui_m1d_xval = [] qui_m1d_yval = [] qui_m2d_xval = [] qui_m2d_yval = [] qui_m3d_xval = [] qui_m3d_yval = [] qui_m4d_xval = [] qui_m4d_yval = [] qui_m1b_xval = [] qui_m1b_yval = [] qui_m2b_xval = [] qui_m2b_yval = [] qui_m3b_xval = [] qui_m3b_yval = [] qui_m4b_xval = [] qui_m4b_yval = [] for row in data: if row['Dv'] 0.65 and row['DSw'] 0.65: * # filling disk-dom arrays* if row['UminV'] 1.3 and row['VminJ'] 1.6 and row['UminV'] 0.88*(row['VminJ']+0.59):#quiescent criteria at particular z if row['Z'] = 0.6 and row['Z'] 0.9:#redshift bin criteria if row['logM'] = 9.7 and row['logM'] 10:#mass subsets for shape in plots qui_m1d_xval.append(row['VminJ']) * # (x) fill the empty list with the data from the appropriate column.* qui_m1d_yval.append(row['UminV']) elif row['logM'] = 10 and row['logM'] 10.5: qui_m2d_xval.append(row['VminJ']) qui_m2d_yval.append(row['UminV']) elif row['logM'] = 10.5 and row['logM'] 10.8: qui_m3d_xval.append(row['VminJ']) qui_m3d_yval.append(row['UminV']) elif row['logM'] = 10.8: qui_m4d_xval.append(row['VminJ']) qui_m4d_yval.append(row['UminV']) if row['Dv'] 0.35 and row['DSw'] 0.65: * # filling bulge-dom arrays* if row['UminV'] 1.3 and row['VminJ'] 1.6 and row['UminV'] 0.88*(row['VminJ']+0.59):#quiescent criteria at particular z if row['Z'] = 0.6 and row['Z'] 0.9:#redshift bin criteria if row['logM'] = 9.7 and row['logM'] 10:#mass subsets for shape in plots qui_m1b_xval.append(row['VminJ']) qui_m1b_yval.append(row['UminV']) elif row['logM'] = 10 and row['logM'] 10.5: qui_m2b_xval.append(row['VminJ']) qui_m2b_yval.append(row['UminV']) elif row['logM'] = 10.5 and row['logM'] 10.8: qui_m3b_xval.append(row['VminJ']) qui_m3b_yval.append(row['UminV']) elif row['logM'] = 10.8: qui_m4b_xval.append(row['VminJ']) qui_m4b_yval.append(row['UminV']) # - Define Star-Forming Subset sf_m1d_xval = [] sf_m1d_yval = [] sf_m2d_xval = [] sf_m2d_yval = [] sf_m3d_xval = [] sf_m3d_yval = [] sf_m4d_xval = [] sf_m4d_yval = [] sf_m1b_xval = [] sf_m1b_yval = [] sf_m2b_xval = [] sf_m2b_yval = [] sf_m3b_xval = [] sf_m3b_yval = [] sf_m4b_xval = [] sf_m4b_yval = [] for row in data: if row['Dv'] 0.65 and row['DSw'] 0.65: # filling disk-dom arrays if row['UminV'] 1.3 or row['VminJ'] 1.6 or row['UminV'] 0.88*(row['VminJ']+0.59):#star forming creteria at particular z if row['Z'] = 0.6 and row['Z'] 0.9:#reshift bin criteria if row['logM'] = 9.7 and row['logM'] 10: